from rest_framework import serializers
from decimal import Decimal
import logging, datetime, json, requests
from random import randint
from django_redis import get_redis_connection

from users.models import CustomerUser, User, Level, ManagerCustomerRelation, CustomerUserViceInviterRecord
from merchants.models import *
from goods.models import *
from activities.models import *
from orders.models import *
from vouchers.models import *
from cashbonus.models import *
from equity_mall.utils.sync_img_to_local import make_qrcode1, make_qrcode3
from equity_mall.utils.utils import random_str, get_sign_contract_url, check_sign_contract_result
from django.db.models import Count, Sum, Max, Min, Avg
from newyears.models import *
from equity_mall.utils.sync_img_to_local import make_qrcode4
from equity_mall.utils.express_utils import KuaiDi100
from equity_mall.utils.utils import redis_scheme_token_wyh
from equity_mall.utils.qiniu_storage import pic_upload
from merchants.utils import create_contract_table

logger = logging.getLogger('django')


class MerchantListModelSerializer(serializers.ModelSerializer):

    contact = serializers.SerializerMethodField(read_only=True)
    is_mall = serializers.SerializerMethodField(read_only=True)
    is_mall_str = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = Merchant
        fields = ('id', 'name', 'wyfMerchantID', 'subject_type', 'contact', 'is_mall', 'is_mall_str')

    def get_is_mall(self, obj):
        if obj.channel_id != 3:
            return 0
        if obj.is_mall == 0:
            return 1
        elif obj.is_mall == 1:
            return 2
        elif obj.is_mall == 5:
            if obj.applyment_state in [1, 5]:
                return 3
            elif obj.applyment_state == 4:
                return 4
            elif obj.applyment_state == 3:
                return 6
            else:
                if obj.verify_state == 1:
                    return 5
                elif obj.verify_state == 3:
                    return 6
                else:
                    if obj.is_mall == 2:
                        return 7
                    else:
                        return 8
        elif obj.is_mall == 2:
            return 7
        else:
            return 8

    def get_is_mall_str(self, obj):
        if obj.channel_id != 3:
            return '不符合'
        if obj.is_mall == 0:
            return '未开通'
        elif obj.is_mall == 1:
            return '待入驻'
        elif obj.is_mall == 5:
            if obj.applyment_state in [1, 5]:
                return '协议待审核'
            elif obj.applyment_state == 4:
                return '商户待签约'
            elif obj.applyment_state == 3:
                return '审核驳回'
            else:
                if obj.verify_state == 1:
                    return '待审核'
                elif obj.verify_state == 3:
                    return '审核驳回'
                else:
                    if obj.is_mall == 2:
                        return '已通过'
                    else:
                        return '封控'
        elif obj.is_mall == 2:
            return '已通过'
        else:
            return '封控'

    def get_contact(self, obj):
        data = {}
        managerName = obj.managerName
        managermobile = obj.managerName
        try:
            user = self.context.get('user', None)
            enter = MerchantEnter.objects.filter(level_id=user.level_id, merchant_id=obj.id).first()
            managerName = enter.managerName
            managermobile = enter.managermobile
        except:
            pass
        data['managerName'] = managerName.replace(managerName[-2], '*', 1)
        data['managermobile'] = f'{managermobile[:3]}****{managermobile[-4:]}'
        return data


class GoodsSerializer(serializers.ModelSerializer):

    # is_launched = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = Goods
        fields = ('id', 'default_image', 'sales', 'price', 'name', 'is_launched')

    # def get_is_launched(self, obj):
    #     try:
    #         if obj.is_launched in [2, 3, 4]:
    #             return obj.is_launched
    #         user = self.context.get('user', None)
    #         launchedgoods = LaunchedGoods.objects.filter(level_id=user.level_id, goods_id=obj.id).first()
    #         if launchedgoods:
    #             return launchedgoods.is_launched
    #         else:
    #             return 0
    #     except:
    #         return 0


class OrderGoodsSerializer(serializers.ModelSerializer):

    default_image = serializers.SerializerMethodField(read_only=True)
    name = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = OrderGoods
        fields = ('id', 'default_image', 'count', 'name', 'price')

    def get_default_image(self, obj):
        try:
            return obj.goods.default_image.url
        except Exception as e:
            logger.error(e)
            return ''

    def get_name(self, obj):
        try:
            return obj.goods.name
        except Exception as e:
            logger.error(e)
            return ''


class OrderInfoSerializer(serializers.ModelSerializer):

    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    state_str = serializers.CharField(source='get_state_display', read_only=True)
    ordergoods_set = OrderGoodsSerializer(many=True)

    class Meta:
        model = OrderInfo
        fields = ('id', 'create_time', 'state', 'state_str', 'total_point', 'ordergoods_set')


class MerchantRetrieveModelSerializer(serializers.ModelSerializer):

    subject_type_str = serializers.CharField(source='get_subject_type_display', read_only=True)
    goods_set = serializers.SerializerMethodField(read_only=True)
    orderinfo_set = serializers.SerializerMethodField(read_only=True)
    contact = serializers.SerializerMethodField(read_only=True)
    merchant_home_qrcode = serializers.SerializerMethodField(read_only=True)
    is_mall = serializers.SerializerMethodField(read_only=True)
    is_mall_str = serializers.SerializerMethodField(read_only=True)
    applyment = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = Merchant
        fields = ('id', 'name', 'wyfMerchantID', 'subject_type', 'subject_type_str', 'goods_set', 'orderinfo_set', 'contact', 'merchant_home_qrcode', 'is_mall', 'is_mall_str',
                  'applyment', 'store_address')

    def get_applyment(self, obj):
        instance = MerchantMallApplyment.objects.filter(applyment_state__in=[1, 3, 2, 4, 5], merchant_id=obj.id).last()
        data = {}
        data['applyment_type_str'] = ''
        data['applyment_type'] = ''
        data['context'] = ''
        data['create_time'] = ''
        data['audit_time'] = ''
        data['verify_time'] = ''
        data['applyment_state'] = ''
        data['applyment_state_str'] = ''
        data['applyment_state1'] = ''
        data['applyment_state_str1'] = ''
        data['contract'] = ''
        data['sign_url'] = ''
        data['reject_reason'] = ''
        data['verify_state'] = ''
        data['verify_state_str'] = ''
        try:
            if instance:
                data['reject_reason'] = instance.reject_reason
                data['applyment_type_str'] = instance.get_applyment_type_display()
                data['applyment_type'] = instance.applyment_type
                if instance.applyment_state in [0, 1, 5]:
                    data['applyment_state_str'] = '待审核'
                    data['applyment_state'] = 1
                    data['applyment_state_str1'] = '待审核'
                    data['applyment_state1'] = 1
                elif instance.applyment_state == 2:
                    data['applyment_state_str'] = '审核通过'
                    data['applyment_state'] = 2
                    data['applyment_state_str1'] = '已签约'
                    data['applyment_state1'] = 2
                elif instance.applyment_state == 3:
                    data['applyment_state_str'] = '已驳回'
                    data['applyment_state'] = 3
                    data['applyment_state_str1'] = '已驳回'
                    data['applyment_state1'] = 3
                else:
                    data['applyment_state_str'] = '待审核'
                    data['applyment_state'] = 1
                    data['applyment_state_str1'] = '待签约'
                    data['applyment_state1'] = 4
                data['context'] = instance.context
                data['create_time'] = instance.create_time.strftime('%Y-%m-%d %H:%M:%S')
                # if instance.applyment_state == 5:
                #     data['applyment_state'] = 1
                #     data['applyment_state_str'] = '审核中'
                # else:
                #     data['applyment_state'] = instance.applyment_state
                #     data['applyment_state_str'] = instance.get_applyment_state_display()
                # try:
                #     data['contract'] = instance.contract.url
                # except:
                #     data['contract'] = ''
                # if instance.applyment_state == 1:
                #     result = get_sign_contract_url(obj.ruiyinxinMerchantID)
                #     if result['result_code'] != 'fail':
                #         if result['data']['open_status'] == 2:
                #             if not instance.sign_url:
                #                 signUrl = result['data']['signUrl']
                #                 sign_url = make_qrcode1(obj.ruiyinxinMerchantID, signUrl, key=None)
                #                 instance.sign_url = sign_url
                #                 data['sign_url'] = f'https://circle.sutpay.cn/{sign_url}'
                #             else:
                #                 data['sign_url'] = instance.sign_url.url
                #             instance.applyment_state = 2
                #             instance.save()
                #             obj.applyment_state = 2
                #             obj.save()
                #         elif result['data']['open_status'] == 3:
                #             instance.applyment_state = 3
                #             instance.reject_reason = result['data']['open_result']
                #             instance.save()
                #             obj.applyment_state = 3
                #             obj.save()
                #             data['sign_url'] = ''
                #         else:
                #             data['sign_url'] = ''
                # elif instance.applyment_state == 4:
                #     data['sign_url'] = instance.sign_url.url
                #     result = check_sign_contract_result(obj.ruiyinxinMerchantID)
                #     if result['data']['sign_status'] == 3:
                #         obj.applyment_state = 1
                #         obj.verify_state = 1
                #         obj.save()
                #         instance.applyment_state = 1
                #         instance.audit_time = datetime.datetime.now()
                #         instance.save()
                data['audit_time'] = instance.audit_time.strftime('%Y-%m-%d %H:%M:%S')
                data['verify_time'] = instance.verify_time.strftime('%Y-%m-%d %H:%M:%S')
        except:
            pass
        return data

    def get_is_mall(self, obj):
        if obj.channel_id != 3:
            return 0
        if obj.is_mall == 0:
            return 1
        elif obj.is_mall == 1:
            return 2
        elif obj.is_mall == 5:
            if obj.applyment_state in [1, 5]:
                return 3
            elif obj.applyment_state == 4:
                return 4
            elif obj.applyment_state == 3:
                return 6
            else:
                if obj.verify_state == 1:
                    return 5
                elif obj.verify_state == 3:
                    return 6
                else:
                    if obj.is_mall == 2:
                        return 7
                    else:
                        return 8
        elif obj.is_mall == 2:
            return 7
        else:
            return 8

    def get_is_mall_str(self, obj):
        # check_merhant_channel = MerchantChannel.objects.filter(merchant_id=obj.id, channel_id=3)
        # if not check_merhant_channel:
        if obj.channel_id != 3:
            return '不符合'
        if obj.is_mall == 0:
            return '未开通'
        elif obj.is_mall == 1:
            return '待入驻'
        elif obj.is_mall == 5:
            if obj.applyment_state in [1, 5]:
                return '协议待审核'
            elif obj.applyment_state == 4:
                return '商户待签约'
            elif obj.applyment_state == 3:
                return '审核驳回'
            else:
                if obj.verify_state == 1:
                    return '待审核'
                elif obj.verify_state == 3:
                    return '审核驳回'
                else:
                    if obj.is_mall == 2:
                        return '已通过'
                    else:
                        return '封控'
        elif obj.is_mall == 2:
            return '已通过'
        else:
            return '封控'

    # def get_contact(self, obj):
    #     data = {}
    #     data['managerName'] = obj.managerName
    #     data['managermobile'] = obj.managermobile
    #     try:
    #         user = self.context.get('user', None)
    #         enter = MerchantEnter.objects.filter(level_id=user.level_id, merchant_id=obj.id).first()
    #         data['managerName'] = enter.managerName
    #         data['managermobile'] = enter.managermobile
    #     except:
    #         pass
    #     return data

    def get_contact(self, obj):
        data = {}
        managerName = obj.managerName
        managermobile = obj.managerName
        try:
            user = self.context.get('user', None)
            enter = MerchantEnter.objects.filter(level_id=user.level_id, merchant_id=obj.id).first()
            managerName = enter.managerName
            managermobile = enter.managermobile
        except:
            pass
        data['managerName'] = managerName.replace(managerName[-2], '*', 1)
        data['managermobile'] = f'{managermobile[:3]}****{managermobile[-4:]}'
        return data

    def get_goods_set(self, obj):
        try:
            user = self.context.get('user', None)
            goods_set = obj.goods_set.all().filter(launchedgoods__level_id=user.level_id).distinct().order_by('-sales')[:4]
            return GoodsSerializer(goods_set, many=True, context={'user': user}).data
        except Exception as e:
            logger.error(e)
            return []

    def get_orderinfo_set(self, obj):
        try:
            user = self.context.get('user', None)
            orderinfo_set = obj.orderinfo_set.filter(level_id=user.level_id, state__in=[3, 2, 12], order_type=1).order_by('-create_time')[:3]
            return OrderInfoSerializer(orderinfo_set, many=True).data
        except Exception as e:
            logger.error(e)
            return []

    def get_merchant_home_qrcode(self, obj):
        try:
            if not obj.merchant_home_url:
                redis_conn = get_redis_connection("scheme")
                access_token = redis_conn.get('wyh_access_token')
                if access_token is None:
                    access_token = redis_scheme_token_wyh()
                else:
                    access_token = access_token.decode()
                url = f'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token={access_token}'
                body = {
                    "page": "pages/sqm_active_store/sqm_active_store",
                    "scene": f"id={obj.id}",
                    "is_hyaline": True
                }
                response = requests.post(url=url, json=body)
                try:
                    if response.json()['errcode'] != 0:
                        access_token = redis_scheme_token_wyh()
                        url = f'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token={access_token}'
                        response = requests.post(url=url, json=body)
                except:
                    pass
                reslut = response.content
                common_qrcode_url = pic_upload(reslut)
                merchant_home_url = f'https://api.sutpay.com/customer/merchant_home/?id={obj.id}'
                # merchant_home_qrcode = f'youhuiquanyi/{obj.wyfMerchantID}/merchant_home.png'
                # common_qrcode_url = make_qrcode(obj.wyfMerchantID, merchant_home_url, merchant_home_qrcode)
                obj.merchant_home_qrcode = common_qrcode_url
                obj.merchant_home_url = merchant_home_url
                obj.save()
                return f'https://circle.sutpay.cn/{common_qrcode_url}'
            else:
                return obj.merchant_home_qrcode.url
        except:
            return ''


class MerchantInfoRetrieveModelSerializer(serializers.ModelSerializer):

    subject_type_str = serializers.CharField(source='get_subject_type_display', read_only=True)
    is_online_str = serializers.SerializerMethodField(read_only=True)
    contact = serializers.SerializerMethodField(read_only=True)
    is_online = serializers.SerializerMethodField(read_only=True)
    is_mall = serializers.SerializerMethodField(read_only=True)
    is_mall_str = serializers.SerializerMethodField(read_only=True)
    applyment = serializers.SerializerMethodField(read_only=True)
    account_number = serializers.SerializerMethodField(read_only=True)
    account_name = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = Merchant
        fields = ('id', 'name', 'wyfMerchantID', 'contact', 'subject_type', 'subject_type_str',
                  'is_online', 'is_online_str', 'store_address', 'account_bank', 'account_number', 'account_name',
                  'card_copy', 'short_name', 'is_mall_str', 'is_mall', 'applyment')

    def get_account_number(self, obj):
        try:
            return f'{obj.account_number[:4]}****{obj.account_number[-4:]}'
        except:
            return ''

    def get_account_name(self, obj):
        try:
            account_name = obj.account_name
            return f'{account_name.replace(account_name[-2], "*", 1)}'
        except:
            return ''

    def get_applyment(self, obj):
        instance = MerchantMallApplyment.objects.filter(applyment_state__in=[1, 3, 2, 4, 5], merchant_id=obj.id).last()
        data = {}
        data['applyment_type_str'] = ''
        data['applyment_type'] = ''
        data['context'] = ''
        data['create_time'] = ''
        data['audit_time'] = ''
        data['verify_time'] = ''
        data['applyment_state'] = ''
        data['applyment_state_str'] = ''
        data['applyment_state1'] = ''
        data['applyment_state_str1'] = ''
        data['contract'] = ''
        data['sign_url'] = ''
        data['reject_reason'] = ''
        data['verify_state'] = ''
        data['verify_state_str'] = ''
        try:
            if instance:
                data['reject_reason'] = instance.reject_reason
                if instance.applyment_state in [0, 1, 5]:
                    data['applyment_state_str'] = '待审核'
                    data['applyment_state'] = 1
                    data['applyment_state_str1'] = '待审核'
                    data['applyment_state1'] = 1
                elif instance.applyment_state == 2:
                    data['applyment_state_str'] = '审核通过'
                    data['applyment_state'] = 2
                    data['applyment_state_str1'] = '已签约'
                    data['applyment_state1'] = 2
                elif instance.applyment_state == 3:
                    data['applyment_state_str'] = '已驳回'
                    data['applyment_state'] = 3
                    data['applyment_state_str1'] = '已驳回'
                    data['applyment_state1'] = 3
                else:
                    data['applyment_state_str'] = '待审核'
                    data['applyment_state'] = 1
                    data['applyment_state_str1'] = '待签约'
                    data['applyment_state1'] = 4
                data['context'] = instance.context
                data['create_time'] = instance.create_time.strftime('%Y-%m-%d %H:%M:%S')
                data['verify_state'] = instance.verify_state
                data['verify_state_str'] = instance.get_verify_state_display()
                # if instance.applyment_state == 5:
                #     data['applyment_state'] = 1
                #     data['applyment_state_str'] = '审核中'
                # else:
                #     data['applyment_state'] = instance.applyment_state
                #     data['applyment_state_str'] = instance.get_applyment_state_display()
                try:
                    data['contract'] = instance.contract.url
                except:
                    data['contract'] = ''
                if instance.applyment_state == 1:
                    result = get_sign_contract_url(obj.ruiyinxinMerchantID)
                    if result['result_code'] != 'fail':
                        if result['data']['open_status'] == 2:
                            if not instance.sign_url:
                                signUrl = result['data']['signUrl']
                                sign_url = make_qrcode1(obj.ruiyinxinMerchantID, signUrl, key=None)
                                instance.sign_url = sign_url
                                data['sign_url'] = f'https://circle.sutpay.cn/{sign_url}'
                            else:
                                data['sign_url'] = instance.sign_url.url
                            instance.applyment_state = 2
                            instance.save()
                            obj.applyment_state = 2
                            obj.save()
                        elif result['data']['open_status'] == 3:
                            instance.applyment_state = 3
                            instance.reject_reason = result['data']['open_result']
                            instance.save()
                            obj.applyment_state = 3
                            obj.save()
                            data['sign_url'] = ''
                        else:
                            data['sign_url'] = ''
                elif instance.applyment_state == 4:
                    data['sign_url'] = instance.sign_url.url
                    result = check_sign_contract_result(obj.ruiyinxinMerchantID)
                    if result['data']['sign_status'] == 3:
                        obj.applyment_state = 1
                        obj.verify_state = 1
                        obj.save()
                        instance.applyment_state = 1
                        instance.audit_time = datetime.datetime.now()
                        instance.save()
                data['audit_time'] = instance.audit_time.strftime('%Y-%m-%d %H:%M:%S')
                data['verify_time'] = instance.verify_time.strftime('%Y-%m-%d %H:%M:%S')
        except:
            pass
        return data

    def get_is_mall(self, obj):
        # check_merhant_channel = MerchantChannel.objects.filter(merchant_id=obj.id, channel_id=3)
        # if not check_merhant_channel:
        if obj.channel_id != 3:
            return 0
        if obj.is_mall == 0:
            return 1
        elif obj.is_mall == 1:
            return 2
        elif obj.is_mall == 5:
            if obj.applyment_state in [1, 5]:
                return 3
            elif obj.applyment_state == 4:
                return 4
            elif obj.applyment_state == 3:
                return 6
            else:
                if obj.verify_state == 1:
                    return 5
                elif obj.verify_state == 3:
                    return 6
                else:
                    if obj.is_mall == 2:
                        return 7
                    else:
                        return 8
        elif obj.is_mall == 2:
            return 7
        else:
            return 8

    def get_is_mall_str(self, obj):
        # check_merhant_channel = MerchantChannel.objects.filter(merchant_id=obj.id, channel_id=3)
        # if not check_merhant_channel:
        if obj.channel_id != 3:
            return '不符合'
        if obj.is_mall == 0:
            return '未开通'
        elif obj.is_mall == 1:
            return '待入驻'
        elif obj.is_mall == 5:
            if obj.applyment_state in [1, 5]:
                return '协议待审核'
            elif obj.applyment_state == 4:
                return '商户待签约'
            elif obj.applyment_state == 3:
                return '审核驳回'
            else:
                if obj.verify_state == 1:
                    return '待审核'
                elif obj.verify_state == 3:
                    return '审核驳回'
                else:
                    if obj.is_mall == 2:
                        return '已通过'
                    else:
                        return '封控'
        elif obj.is_mall == 2:
            return '已通过'
        else:
            return '封控'

    def get_is_online(self, obj):
        try:
            if obj.is_mall != 2:
                return 1
            else:
                user = self.context.get('user', None)
                merchant_enter = MerchantEnter.objects.filter(merchant_id=obj.id, level_id=user.level_id).first()
                return merchant_enter.is_online
        except Exception as e:
            logger.error(e)
            return 3

    def get_is_online_str(self, obj):
        try:
            if obj.is_mall != 2:
                return '未上架'
            else:
                user = self.context.get('user', None)
                merchant_enter = MerchantEnter.objects.filter(merchant_id=obj.id, level_id=user.level_id).first()
                return merchant_enter.get_is_online_display()
        except Exception as e:
            logger.error(e)
            return '已下架'

    def get_level_name(self, obj):
        try:
            return obj.level.name
        except:
            return ''

    # def get_contact(self, obj):
    #     data = {}
    #     data['managerName'] = obj.managerName
    #     data['managermobile'] = obj.managermobile
    #     if obj.level:
    #         data['level_name'] = obj.level.name
    #     else:
    #         data['level_name'] = ''
    #     try:
    #         user = self.context.get('user', None)
    #         enter = MerchantEnter.objects.filter(level_id=user.level_id, merchant_id=obj.id).first()
    #         data['managerName'] = enter.managerName
    #         data['managermobile'] = enter.managermobile
    #         data['level_name'] = enter.level.name
    #     except:
    #         pass
    #     return data

    def get_contact(self, obj):
        data = {}
        managerName = obj.managerName
        managermobile = obj.managerName
        if obj.level:
            data['level_name'] = obj.level.name
        else:
            data['level_name'] = ''
        try:
            user = self.context.get('user', None)
            enter = MerchantEnter.objects.filter(level_id=user.level_id, merchant_id=obj.id).first()
            managerName = enter.managerName
            managermobile = enter.managermobile
            data['level_name'] = enter.level.name
        except:
            pass
        data['managerName'] = managerName.replace(managerName[-2], '*', 1)
        data['managermobile'] = f'{managermobile[:3]}****{managermobile[-4:]}'
        return data


class OrderInfoListModelSerializer(serializers.ModelSerializer):

    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    state_str = serializers.CharField(source='get_state_display', read_only=True)
    order_species_str = serializers.SerializerMethodField(read_only=True)
    ordergoods_set = OrderGoodsSerializer(many=True)
    merchant_name = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = OrderInfo
        fields = ['id', 'create_time', 'state_str', 'ordergoods_set', 'state', 'merchant_name', 'order_species', 'order_species_str']

    def get_order_species_str(self, obj):
        try:
            if obj.order_species == 1:
                return '邮米'
            else:
                return '普通'
        except:
            return '普通'

    def get_merchant_name(self, obj):
        try:
            return obj.merchant.name
        except:
            return ''


class GoodsCouponsModelSerializer(serializers.ModelSerializer):

    status_str = serializers.CharField(source='get_status_display', read_only=True)
    coupons_id = serializers.SerializerMethodField(read_only=True)
    validity_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)

    class Meta:
        model = GoodsCoupons
        fields = ['id', 'status_str', 'status', 'coupons_id', 'validity_time']

    def get_coupons_id(self, obj):
        if obj.status == 1:
            return obj.coupons_id[:8] + '********'
        else:
            return obj.coupons_id


class OrderAddressModelSerializer(serializers.ModelSerializer):

    receiver = serializers.SerializerMethodField(read_only=True)
    mobile = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = OrderAddress
        fields = ['id', 'receiver', 'place', 'mobile', 'province', 'city', 'district']

    def get_receiver(self, obj):
        try:
            receiver = obj.receiver
            return receiver.replace(receiver[-2], '*', 1)
        except:
            return ''

    def get_mobile(self, obj):
        try:
            return f'{obj.mobile[:3]}****{obj.mobile[-4:]}'
        except:
            return ''


class ExpressPlanModelSerializer(serializers.ModelSerializer):

    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)

    class Meta:
        model = ExpressPlan
        fields = ('id', 'create_time', 'remark')


class ExpressModelSerializer(serializers.ModelSerializer):

    deliverystatus_str = serializers.CharField(source='get_deliverystatus_display', read_only=True)
    express_name = serializers.SerializerMethodField(read_only=True)
    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    expressplan_set = serializers.SerializerMethodField(read_only=True)
    deliverystatus = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = Express
        fields = ('id', 'deliverystatus', 'deliverystatus_str', 'express_number', 'express_name', 'create_time', 'expressplan_set')

    def get_deliverystatus(self, obj):
        try:
            if obj.deliverystatus in [0, 1, 5, 2, 6]:
                redis_conn = get_redis_connection("express_number")
                express_number_flag = redis_conn.get("express_number_%s" % obj.express_number)
                if not express_number_flag:
                    redis_conn.setex('express_number_%s' % obj.express_number, 21600, 1)
                    order = ExpressOrderRelevance.objects.filter(express_id=obj.id).first()
                    phone = OrderAddress.objects.filter(order_id=order.order_id).first()
                    if phone:
                        result = KuaiDi100().track(obj.express_type.express_type, obj.express_number, phone.mobile[-4:])
                    else:
                        result = KuaiDi100().track(obj.express_type.express_type, obj.express_number)
                    if result['status'] == '200':
                        obj.deliverystatus = result['state']
                        obj.save()
                        if obj.deliverystatus == 3:
                            try:
                                order = obj.order
                                user = order.user
                            except:
                                pass
                        for i in result['data']:
                            plan_data = {}
                            plan_data['express_id'] = obj.id
                            plan_data['create_time'] = i['time']
                            plan_data['remark'] = i['context']
                            ExpressPlan.objects.get_or_create(defaults=plan_data, create_time=i['time'], express_id=obj.id)
                        if str(obj.deliverystatus) == "3":
                            try:
                                sign_time = ExpressPlan.objects.filter(express_id=obj.id).aggregate(Max('create_time'))['create_time__max']
                                obj.sign_time = sign_time
                                obj.save()
                            except:
                                pass
                    else:
                        obj.deliverystatus = 9
                        obj.save()
                        ExpressPlan.objects.create(remark=result['message'], create_time=datetime.datetime.now(), express_id=obj.id)
            return obj.deliverystatus
        except:
            return obj.deliverystatus

    def get_expressplan_set(self, obj):
        try:
            expressplan_set = obj.expressplan_set.all().order_by('-create_time')
            return ExpressPlanModelSerializer(expressplan_set, many=True).data
        except:
            return []

    def get_express_name(self, obj):
        try:
            return obj.express_type.express_type_name
        except:
            return ''


class AfterSaleApplicationFormModelSerializer(serializers.ModelSerializer):

    form_status_str = serializers.CharField(source='get_form_status_display', read_only=True)
    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    refund_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    img_array = serializers.SerializerMethodField(read_only=True)
    reason = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = AfterSaleApplicationForm
        fields = ['id', 'form_status', 'form_status_str', 'create_time', 'description', 'refund_money', 'return_msg',
                  'refund_time', 'reason', 'img_array', 'application_num']

    def get_reason(self, obj):
        try:
            return obj.reason.name
        except:
            return ''

    def get_img_array(self, obj):
        data = []
        try:
            queryset = AfterSaleApplicationFormImg.objects.filter(applicationform_id=obj.id)
            for query in queryset:
                data.append(query.img.url)
        except:
            pass
        return data


class OrderInfoRetrieveModelSerializer(serializers.ModelSerializer):

    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    state_str = serializers.CharField(source='get_state_display', read_only=True)
    ordergoods_set = OrderGoodsSerializer(many=True)
    goodscoupons_set = serializers.SerializerMethodField(read_only=True)
    level_name = serializers.SerializerMethodField(read_only=True)
    merchant_name = serializers.SerializerMethodField(read_only=True)
    customeruser_realname = serializers.SerializerMethodField(read_only=True)
    orderaddress = serializers.SerializerMethodField(read_only=True)
    express_info = serializers.SerializerMethodField(read_only=True)
    after_sale = serializers.SerializerMethodField(read_only=True)
    order_species_str = serializers.SerializerMethodField(read_only=True)
    reserved_mobile = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = OrderInfo
        fields = ['id', 'create_time', 'state_str', 'ordergoods_set', 'total_price', 'goodscoupons_set', 'reserved_mobile', 'level_name', 'merchant_name',
                  'customeruser_realname', 'orderaddress', 'express_info', 'order_type', 'state', 'order_id', 'after_sale', 'order_species_str', 'order_species']

    def get_reserved_mobile(self, obj):
        try:
            mobile = obj.reserved_mobile
            return f'{mobile[:3]}****{mobile[-4:]}'
        except:
            return ''

    def get_order_species_str(self, obj):
        try:
            if obj.order_species == 1:
                return '邮米'
            else:
                return '普通'
        except:
            return '普通'

    def get_after_sale(self, obj):
        try:
            after_sale = AfterSaleApplicationForm.objects.exclude(form_status=4).filter(order_id=obj.id).last()
            if after_sale:
                return AfterSaleApplicationFormModelSerializer(after_sale).data
            else:
                return {}
        except:
            return {}

    def get_express_info(self, obj):
        try:
            express_id_list = ExpressOrderRelevance.objects.filter(order_id=obj.id).values_list('express_id', flat=True)
            express_set = Express.objects.filter(id__in=list(express_id_list))
            return ExpressModelSerializer(express_set, many=True).data
        except:
            return []

    def get_orderaddress(self, obj):
        try:
            orderaddress = obj.orderaddress
            if orderaddress:
                return OrderAddressModelSerializer(orderaddress).data
            else:
                return {}
        except:
            return {}

    def get_customeruser_realname(self, obj):
        try:
            customeruser_realname = obj.customer_user.realname
            if customeruser_realname:
                return customeruser_realname
            else:
                return ''
        except:
            return ''

    def get_merchant_name(self, obj):
        try:
            return obj.merchant.name
        except:
            return ''

    def get_goodscoupons_set(self, obj):
        try:
            goodscoupons_set = obj.goodscoupons_set.all().order_by('status')
            return GoodsCouponsModelSerializer(goodscoupons_set, many=True).data
        except:
            return []

    def get_level_name(self, obj):
        try:
            return obj.level.name
        except:
            return ''


class UserInfoModelSerializer(serializers.ModelSerializer):

    level_name = serializers.SerializerMethodField(read_only=True)
    role_name = serializers.SerializerMethodField(read_only=True)
    invite_qrcode = serializers.SerializerMethodField(read_only=True)
    is_admin = serializers.SerializerMethodField(read_only=True)
    shop_qrcode = serializers.SerializerMethodField(read_only=True)
    is_first_audit = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = User
        fields = ['id', 'account', 'nickname', 'mobile', 'level_name', 'avatar', 'username', 'role_name', 'role_id', 'invite_qrcode', 'is_admin', 'shop_qrcode', 'is_first_audit',
                  'is_agreement']

    def get_is_first_audit(self, obj):
        try:
            if obj.role_id == 2 and obj.level.level in [0,3]:
                return 1
            return 0
        except:
            return 0

    def get_level_name(self, obj):
        try:
            return obj.level.name
        except:
            return ''

    def get_role_name(self, obj):
        try:
            return obj.role.name
        except:
            return ''

    def get_is_admin(self, obj):
        try:
            return obj.role.is_admin
        except:
            return ''

    def get_invite_qrcode(self, obj):
        try:
            if obj.role.is_admin == 1:
                if not obj.identify:
                    identify = f'{obj.mobile}{random_str(22)}'
                    invite_url = f'https://api.sutpay.com/manager/invite_manager/?user_id={identify}'
                    invite_qrcode = f'youhuiquanyi/{obj.mobile}/invite_url.png'
                    common_qrcode_url = make_qrcode3(obj.mobile, invite_url, invite_qrcode)
                    obj.invite_qrcode = invite_qrcode
                    obj.invite_url = invite_url
                    obj.identify = identify
                    obj.save()
                    return f'https://circle.sutpay.cn/{invite_qrcode}'
                else:
                    return obj.invite_qrcode.url
            else:
                return ''
        except:
            return ''

    def get_shop_qrcode(self, obj):
        try:
            level = obj.level
            if not level.shop_qrcode:
                shop_url = f'https://qrcode.sutpay.com/business/institution/goods/?level_id={level.id}'
                shop_qrcode = make_qrcode1(obj.mobile, shop_url, None)
                level.shop_qrcode = shop_qrcode
                level.shop_url = shop_url
                level.save()
                return f'https://circle.sutpay.cn/{shop_qrcode}'
            else:
                return level.shop_qrcode.url
        except:
            return ''


class AliDiscountCouponLevelListModelSerializer(serializers.ModelSerializer):

    activity = serializers.SerializerMethodField(read_only=True)
    level_name = serializers.SerializerMethodField(read_only=True)
    level = serializers.SerializerMethodField(read_only=True)
    p_max_number = serializers.SerializerMethodField(read_only=True)
    p_remain_number = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = AliDiscountCouponLevel
        fields = ['id', 'activity', 'max_number', 'take_number', 'remain_number', 'p_max_number', 'p_take_number', 'p_remain_number', 'level', 'level_name']

    def get_p_max_number(self, obj):
        try:
            activity = obj.activity
            if activity.coupon_way == 4:
                return activity.max_number
            else:
                return obj.p_max_number
        except:
            return ''

    def get_p_remain_number(self, obj):
        try:
            activity = obj.activity
            if activity.coupon_way == 4:
                return activity.remain_number
            else:
                return obj.p_remain_number
        except:
            return ''

    def get_level_name(self, obj):
        try:
            return obj.level.name
        except:
            return ''

    def get_level(self, obj):
        try:
            return obj.level.level
        except:
            return ''

    def get_activity(self, obj):
        data = {}
        data['activity_name'] = ''
        data['template_id'] = ''
        data['floor_amount'] = ''
        data['available_time'] = ''
        data['coupon_status'] = ''
        data['coupon_status_str'] = ''
        try:
            activity = obj.activity
            now_date = datetime.datetime.now()
            if activity.coupon_status in [1, 4]:
                if activity.publish_end_time < now_date:
                    activity.coupon_status = 2
                    activity.save()
            # elif activity.coupon_status == 3:
            #     if activity.publish_start_time < now_date:
            #         activity.coupon_status = 1
            #         activity.save()
            data['activity_name'] = activity.activity_name
            data['template_id'] = activity.template_id
            data['floor_amount'] = activity.floor_amount
            data['available_time'] = f'{activity.publish_start_time.strftime("%m/%d %H:%M:%S")}-{activity.publish_end_time.strftime("%m/%d %H:%M:%S")}'
            data['coupon_status'] = activity.coupon_status
            data['coupon_status_str'] = activity.get_coupon_status_display()
        except:
            pass
        return data


class AliDiscountCouponLevelRetrieveModelSerializer(serializers.ModelSerializer):

    activity = serializers.SerializerMethodField(read_only=True)
    level = serializers.SerializerMethodField(read_only=True)
    level_name = serializers.SerializerMethodField(read_only=True)
    p_unclaimed_number = serializers.SerializerMethodField(read_only=True)
    p_wait_number = serializers.SerializerMethodField(read_only=True)
    p_wait_rate = serializers.SerializerMethodField(read_only=True)
    p_unclaimed_rate = serializers.SerializerMethodField(read_only=True)
    p_use_rate = serializers.SerializerMethodField(read_only=True)
    p_remain_rate = serializers.SerializerMethodField(read_only=True)
    remain_number = serializers.SerializerMethodField(read_only=True)
    max_number = serializers.SerializerMethodField(read_only=True)
    p_max_number = serializers.SerializerMethodField(read_only=True)
    p_remain_number = serializers.SerializerMethodField(read_only=True)
    is_register = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = AliDiscountCouponLevel
        fields = ['id', 'activity', 'max_number', 'take_number', 'remain_number', 'level', 'p_max_number', 'p_take_number', 'p_remain_number',
                  'p_use_number', 'p_unclaimed_number', 'p_wait_number', 'level_name', 'p_wait_rate', 'p_unclaimed_rate', 'p_use_rate', 'p_remain_rate',
                  'is_register']

    def get_is_register(self, obj):
        try:
            activity = self.context.get('activity', None)
            if activity.drawdown_platform_id == 3:
                return 0
            else:
                return 1
        except:
            return 1

    def get_p_max_number(self, obj):
        try:
            activity = self.context.get('activity', None)
            if activity.coupon_way == 4:
                return activity.max_number
            else:
                return obj.p_max_number
        except:
            return ''

    def get_p_remain_number(self, obj):
        try:
            activity = self.context.get('activity', None)
            if activity.coupon_way == 4:
                return activity.remain_number
            else:
                return obj.p_remain_number
        except:
            return ''

    def get_remain_number(self, obj):
        try:
            activity = self.context.get('activity', None)
            if activity.coupon_way == 4:
                if obj.is_auth:
                    return activity.remain_number
                else:
                    return 0
            else:
                return obj.remain_number
        except:
            return ''

    def get_max_number(self, obj):
        try:
            activity = self.context.get('activity', None)
            if activity.coupon_way == 4:
                if obj.is_auth:
                    return activity.max_number
                else:
                    return 0
            else:
                return obj.remain_number
        except:
            return ''

    def get_p_remain_rate(self, obj):
        try:
            activity = self.context.get('activity', None)
            if activity.coupon_way == 4:
                p_remain_rate = f"{(Decimal(activity.remain_number / activity.max_number) * Decimal('100')).quantize(Decimal('0.00'))}%"
            else:
                p_remain_rate = f"{(Decimal(obj.p_remain_number / obj.p_max_number) * Decimal('100')).quantize(Decimal('0.00'))}%"
            return p_remain_rate
        except:
            return ''

    def get_p_use_rate(self, obj):
        try:
            activity = self.context.get('activity', None)
            if activity.coupon_way == 4:
                p_use_rate = f"{(Decimal(obj.p_use_number / activity.max_number) * Decimal('100')).quantize(Decimal('0.00'))}%"
            else:
                p_use_rate = f"{(Decimal(obj.p_use_number / obj.p_max_number) * Decimal('100')).quantize(Decimal('0.00'))}%"
            return p_use_rate
        except:
            return ''

    def get_p_unclaimed_rate(self, obj):
        try:
            activity = self.context.get('activity', None)
            if activity.coupon_way == 4:
                p_unclaimed_number = obj.p_take_number - obj.p_receive_number
                p_unclaimed_rate = f"{(Decimal(p_unclaimed_number / activity.max_number) * Decimal('100')).quantize(Decimal('0.00'))}%"
            else:
                p_unclaimed_number = obj.p_take_number - obj.p_receive_number
                p_unclaimed_rate = f"{(Decimal(p_unclaimed_number / obj.p_max_number) * Decimal('100')).quantize(Decimal('0.00'))}%"
            return p_unclaimed_rate
        except:
            return ''

    def get_p_wait_rate(self, obj):
        try:
            activity = self.context.get('activity', None)
            if activity.coupon_way == 4:
                p_wait_number = obj.p_receive_number - obj.p_use_number
                p_wait_rate = f"{(Decimal(p_wait_number / activity.max_number) * Decimal('100')).quantize(Decimal('0.00'))}%"
            else:
                p_wait_number = obj.p_receive_number - obj.p_use_number
                p_wait_rate = f"{(Decimal(p_wait_number / obj.p_max_number) * Decimal('100')).quantize(Decimal('0.00'))}%"
            return p_wait_rate
        except:
            return ''

    def get_p_unclaimed_number(self, obj):
        try:
            p_unclaimed_number = obj.p_take_number - obj.p_receive_number
            return p_unclaimed_number
        except:
            return ''

    def get_p_wait_number(self, obj):
        try:
            p_wait_number = obj.p_receive_number - obj.p_use_number
            return p_wait_number
        except:
            return ''

    def get_level(self, obj):
        try:
            return obj.level.level
        except:
            return ''

    def get_level_name(self, obj):
        try:
            return obj.level.name
        except:
            return ''

    def get_activity(self, obj):
        data = {}
        data['id'] = ''
        data['activity_name'] = ''
        data['template_id'] = ''
        data['floor_amount'] = ''
        data['available_time'] = ''
        data['usetime_type'] = ''
        data['bankcard_type'] = ''
        data['join_limit_by_user'] = ''
        data['coupon_status'] = ''
        data['coupon_status_str'] = ''
        data['amount'] = ''
        data['principal_name'] = ''
        data['activity_zone_qrcode'] = ''
        try:
            activity = obj.activity
            data['id'] = activity.id
            data['activity_name'] = activity.activity_name
            data['template_id'] = activity.template_id
            data['floor_amount'] = activity.floor_amount
            data['available_time'] = f'{activity.publish_start_time.strftime("%Y.%m.%d %H:%M:%S")}-{activity.publish_end_time.strftime("%Y.%m.%d %H:%M:%S")}'
            data['coupon_status'] = activity.coupon_status
            data['coupon_status_str'] = activity.get_coupon_status_display()
            data['coupon_type_str'] = activity.get_coupon_type_display()
            data['coupon_type'] = activity.coupon_type
            if activity.coupon_type != 6:
                data['amount'] = activity.amount
            else:
                data['amount'] = '商品兑换券'
            if activity.coupon_type in [2, 6, 8]:
                channelcommonvoucher = activity.alidiscountcouponchannelcommonvoucher
                data['discount_type'] = channelcommonvoucher.get_discount_type_display()
                data['bankcard_type'] = channelcommonvoucher.get_bankcard_type_display()
                data['principal_name'] = channelcommonvoucher.principal_name
                if channelcommonvoucher.usetime_type == 2:
                    data['usetime_type'] = f'固定时间段{channelcommonvoucher.start_fixed_time.strftime("%Y.%m.%d %H:%M:%S")}-{channelcommonvoucher.end_fixed_time.strftime("%Y.%m.%d %H:%M:%S")}'
                elif channelcommonvoucher.usetime_type == 3:
                    data['usetime_type'] = f'领取后立即生效有效时间{channelcommonvoucher.invalid_day}天'
                else:
                    data['usetime_type'] = f'领取后次日凌晨生效有效时间{channelcommonvoucher.invalid_day}天'
                if channelcommonvoucher.join_limit_by_user == 1:
                    data['join_limit_by_user'] = f'活动期间每个用户可参与{channelcommonvoucher.join_limit_by_user_count}次'
                else:
                    data['join_limit_by_user'] = '不限制'
                if channelcommonvoucher.join_limit_by_bay == 1:
                    data['join_limit_by_bay'] = f'每个用户每日可参与{channelcommonvoucher.join_limit_by_bay_count}次'
                elif channelcommonvoucher.join_limit_by_bay == 2:
                    data['join_limit_by_bay'] = f'每个用户每月可参与{channelcommonvoucher.join_limit_by_bay_count}次'
                elif channelcommonvoucher.join_limit_by_bay == 4:
                    data['join_limit_by_bay'] = f'每个用户每周可参与{channelcommonvoucher.join_limit_by_bay_count}次'
                else:
                    data['join_limit_by_bay'] = '不限制'
            if activity.coupon_channel == 2 and activity.goods_tag:
                if not activity.activity_zone_qrcode:
                    redis_conn = get_redis_connection("scheme")
                    access_token = redis_conn.get('wyh_access_token')
                    if access_token is None:
                        access_token = redis_scheme_token_wyh()
                    else:
                        access_token = access_token.decode()
                    url = f'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token={access_token}'
                    body = {
                        "page": "pages/coupon_pro_list/coupon_pro_list",
                        "scene": f"activity_id={activity.id}",
                        "is_hyaline": True
                    }
                    response = requests.post(url=url, json=body)
                    try:
                        if response.json()['errcode'] != 0:
                            access_token = redis_scheme_token_wyh()
                            url = f'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token={access_token}'
                            response = requests.post(url=url, json=body)
                    except:
                        pass
                    reslut = response.content
                    activity_zone_qrcode = pic_upload(reslut)
                    activity.activity_zone_qrcode = activity_zone_qrcode
                    activity.save()
                    data['activity_zone_qrcode'] = f'https://circle.sutpay.cn/{activity_zone_qrcode}'
                else:
                    data['activity_zone_qrcode'] = activity.activity_zone_qrcode.url
            data['drawdown_platform'] = activity.drawdown_platform.platform_name
        except:
            pass
        return data


class AliDiscountCouponLevelStatisticalModelSerializer(serializers.ModelSerializer):

    level_name = serializers.SerializerMethodField(read_only=True)
    p_unclaimed_number = serializers.SerializerMethodField(read_only=True)
    p_wait_number = serializers.SerializerMethodField(read_only=True)
    p_wait_rate = serializers.SerializerMethodField(read_only=True)
    p_unclaimed_rate = serializers.SerializerMethodField(read_only=True)
    p_use_rate = serializers.SerializerMethodField(read_only=True)
    p_remain_rate = serializers.SerializerMethodField(read_only=True)
    p_remain_number = serializers.SerializerMethodField(read_only=True)
    p_max_number = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = AliDiscountCouponLevel
        fields = ['id', 'level_name', 'p_max_number', 'p_use_number', 'p_remain_number', 'p_unclaimed_number', 'p_wait_number', 'p_wait_rate', 'p_unclaimed_rate', 'p_use_rate', 'p_remain_rate']

    def get_p_max_number(self, obj):
        try:
            activity = self.context.get('activity', None)
            if activity.coupon_way == 4:
                return activity.max_number
            else:
                return obj.p_max_number
        except:
            return ''

    def get_p_remain_number(self, obj):
        try:
            activity = self.context.get('activity', None)
            if activity.coupon_way == 4:
                return activity.remain_number
            else:
                return obj.p_remain_number
        except:
            return ''

    def get_p_remain_rate(self, obj):
        try:
            activity = self.context.get('activity', None)
            if activity.coupon_way == 4:
                p_remain_rate = f"{(Decimal(activity.remain_number / activity.max_number) * Decimal('100')).quantize(Decimal('0.00'))}%"
            else:
                p_remain_rate = f"{(Decimal(obj.p_remain_number / obj.p_max_number) * Decimal('100')).quantize(Decimal('0.00'))}%"
            return p_remain_rate
        except:
            return ''

    def get_p_use_rate(self, obj):
        try:
            activity = self.context.get('activity', None)
            if activity.coupon_way == 4:
                p_use_rate = f"{(Decimal(obj.p_use_number / activity.max_number) * Decimal('100')).quantize(Decimal('0.00'))}%"
            else:
                p_use_rate = f"{(Decimal(obj.p_use_number / obj.p_max_number) * Decimal('100')).quantize(Decimal('0.00'))}%"
            return p_use_rate
        except:
            return ''

    def get_p_unclaimed_rate(self, obj):
        try:
            activity = self.context.get('activity', None)
            if activity.coupon_way == 4:
                p_unclaimed_number = obj.p_take_number - obj.p_receive_number
                p_unclaimed_rate = f"{(Decimal(p_unclaimed_number / activity.max_number) * Decimal('100')).quantize(Decimal('0.00'))}%"
            else:
                p_unclaimed_number = obj.p_take_number - obj.p_receive_number
                p_unclaimed_rate = f"{(Decimal(p_unclaimed_number / obj.p_max_number) * Decimal('100')).quantize(Decimal('0.00'))}%"
            return p_unclaimed_rate
        except:
            return ''

    def get_p_wait_rate(self, obj):
        try:
            activity = self.context.get('activity', None)
            if activity.coupon_way == 4:
                p_wait_number = obj.p_receive_number - obj.p_use_number
                p_wait_rate = f"{(Decimal(p_wait_number / activity.max_number) * Decimal('100')).quantize(Decimal('0.00'))}%"
            else:
                p_wait_number = obj.p_receive_number - obj.p_use_number
                p_wait_rate = f"{(Decimal(p_wait_number / obj.p_max_number) * Decimal('100')).quantize(Decimal('0.00'))}%"
            return p_wait_rate
        except:
            return ''

    def get_level_name(self, obj):
        try:
            return obj.level.name
        except:
            return ''

    def get_p_unclaimed_number(self, obj):
        try:
            p_unclaimed_number = obj.p_take_number - obj.p_receive_number
            return p_unclaimed_number
        except:
            return ''

    def get_p_wait_number(self, obj):
        try:
            p_wait_number = obj.p_receive_number - obj.p_use_number
            return p_wait_number
        except:
            return ''


class AliDiscountCouponInfoListModelSerializer(serializers.ModelSerializer):

    gmt_create = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    gmt_distributed = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    status_str = serializers.CharField(source='get_status_display', read_only=True)
    mobile = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = AliDiscountCouponInfo
        fields = ['id', 'gmt_create', 'mobile', 'status', 'status_str', 'gmt_distributed']

    def get_mobile(self, obj):
        try:
            return f'{obj.mobile[:3]}****{obj.mobile[-4:]}'
        except:
            return ''


class AliDiscountCouponInfoRetrieveModelSerializer(serializers.ModelSerializer):

    gmt_create = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    gmt_use = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    gmt_distributed = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    gmt_undo = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    floor_amount = serializers.SerializerMethodField(read_only=True)
    status_str = serializers.CharField(source='get_status_display', read_only=True)
    companyuser_nickname = serializers.SerializerMethodField(read_only=True)
    customeruser_realname = serializers.SerializerMethodField(read_only=True)
    activity_name = serializers.SerializerMethodField(read_only=True)
    level_name = serializers.SerializerMethodField(read_only=True)
    mobile = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = AliDiscountCouponInfo
        fields = ['id', 'gmt_create', 'mobile', 'status', 'status_str', 'floor_amount', 'companyuser_nickname',
                  'activity_name', 'gmt_use', 'gmt_distributed', 'gmt_undo', 'level_name', 'customeruser_realname']

    def get_mobile(self, obj):
        try:
            return f'{obj.mobile[:3]}****{obj.mobile[-4:]}'
        except:
            return ''

    def get_level_name(self, obj):
        try:
            return obj.level.name
        except:
            return ''

    def get_floor_amount(self, obj):
        try:
            return obj.alidiscountcoupon.floor_amount
        except:
            return ''

    def get_activity_name(self, obj):
        try:
            return obj.alidiscountcoupon.activity_name
        except:
            return ''

    def get_companyuser_nickname(self, obj):
        try:
            nickname = obj.companyuser.nickname
            return nickname.replace(nickname[-2], '*', 1)
        except:
            return ''

    def get_customeruser_realname(self, obj):
        try:
            realname = obj.customer_user.realname
            return realname.replace(realname[-2], '*', 1)
        except:
            return ''


class UserInfoSerializer(serializers.ModelSerializer):

    class Meta:
        model = User
        fields = ('id', 'username', 'mobile', 'header')


class GoodsListModelSerializer(serializers.ModelSerializer):

    goods_is_launched = serializers.SerializerMethodField(read_only=True)
    is_coupon = serializers.SerializerMethodField(read_only=True)
    merchant_name = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = Goods
        fields = ('id', 'name', 'default_image', 'price', 'sales', 'is_launched', 'goods_is_launched', 'is_coupon', 'merchant_name')

    def get_merchant_name(self, obj):
        try:
            return obj.merchant.name
        except:
            return ''

    def get_is_coupon(self, obj):
        try:
            return 0
        except:
            return 0

    def get_goods_is_launched(self, obj):
        try:
            user = self.context.get('user', None)
            launchedgoods = LaunchedGoods.objects.filter(level_id=user.level_id, goods_id=obj.id).first()
            if launchedgoods:
                return launchedgoods.is_launched
            else:
                launchedgoods_data = {}
                launchedgoods_data['level_id'] = user.level_id
                launchedgoods_data['goods_id'] = obj.id
                launchedgoods_data['is_launched'] = 0
                launchedgoods_data['name'] = obj.name
                launchedgoods_data['category_id'] = 1
                launchedgoods_data['stock'] = 0
                launched_goods, create = LaunchedGoods.objects.get_or_create(defaults=launchedgoods_data, level_id=user.level_id, goods_id=obj.id)
                return 0
        except:
            return 0


class GoodsRetrieveModelSerializer(serializers.ModelSerializer):

    goodsimage_set = serializers.SerializerMethodField(read_only=True)
    merchant_name = serializers.SerializerMethodField(read_only=True)
    desc_detail = serializers.SerializerMethodField(read_only=True)
    market_code = serializers.SerializerMethodField(read_only=True)
    stock = serializers.SerializerMethodField(read_only=True)
    business_no = serializers.SerializerMethodField(read_only=True)
    goods_is_launched = serializers.SerializerMethodField(read_only=True)
    reject_reason = serializers.SerializerMethodField(read_only=True)
    alidiscountcoupon_set = serializers.SerializerMethodField(read_only=True)
    goods_tag_id = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = Goods
        fields = ('id', 'name', 'default_image', 'price', 'sales', 'goodsimage_set', 'desc_detail', 'market_price', 'merchant_name', 'market_code',
                  'manufacturer', 'specifications', 'stock', 'business_no', 'caption', 'is_launched', 'reject_reason', 'goods_is_launched',
                  'alidiscountcoupon_set', 'goods_tag', 'goods_tag_id', 'merchant_id', 'proof', 'desc_pack')

    def get_goods_tag_id(self, obj):
        try:
            if not obj.goods_tag:
                return ''
            user = self.context.get('user', None)
            goods_tag_activity_level = GoodsTagActivityLevelRelation.objects.filter(goods_tag_activity__goods_tag=obj.goods_tag, level_id=user.level_id).first()
            if goods_tag_activity_level:
                return goods_tag_activity_level.id
            else:
                return ''
        except:
            return ''

    def get_alidiscountcoupon_set(self, obj):
        data = []
        try:
            date_now = datetime.datetime.now()
            goods_tag = obj.goods_tag
            if not goods_tag:
                return data
            queryset = AliDiscountCoupon.objects.filter(coupon_status__in=[1, 3], publish_end_time__gte=date_now, goods_tag=goods_tag)[:4]
            for activity in queryset:
                data.append({
                    "activity_name": activity.activity_name,
                    "template_id": activity.template_id,
                    "floor_amount": activity.floor_amount,
                })
            return data
        except:
            return data

    def get_reject_reason(self, obj):
        try:
            if obj.is_launched == 3:
                applyment = obj.goodsmodifyapplyment_set.all().filter(applyment_status=3).last()
                return applyment.reject_reason
            else:
                return ''
        except:
            return ''

    def get_goods_is_launched(self, obj):
        try:
            user = self.context.get('user', None)
            launchedgoods = LaunchedGoods.objects.filter(level_id=user.level_id, goods_id=obj.id).first()
            if launchedgoods:
                return launchedgoods.is_launched
            else:
                launchedgoods_data = {}
                launchedgoods_data['level_id'] = user.level_id
                launchedgoods_data['goods_id'] = obj.id
                launchedgoods_data['is_launched'] = 0
                launchedgoods_data['name'] = obj.name
                launchedgoods_data['category_id'] = 1
                launchedgoods_data['stock'] = 0
                launched_goods, create = LaunchedGoods.objects.get_or_create(defaults=launchedgoods_data, level_id=user.level_id, goods_id=obj.id)
                return 0
        except:
            return 0

    def get_goodsimage_set(self, obj):
        data = []
        try:
            goodsimage_set = obj.goodsimage_set.all()
            for goodsimage in goodsimage_set:
                data.append(goodsimage.image.url)
        except:
            pass
        return data

    def get_merchant_name(self, obj):
        try:
            return obj.merchant.name
        except:
            return ''

    def get_business_no(self, obj):
        try:
            return obj.merchant.wyfMerchantID
        except:
            return ''

    def get_desc_detail(self, obj):
        try:
            return json.loads(obj.desc_detail.replace("'", '"'))
        except:
            return obj.desc_detail

    def get_stock(self, obj):
        try:
            user = self.context.get('user', None)
            launchedgoods = LaunchedGoods.objects.filter(level_id=user.level_id, goods_id=obj.id).first()
            return launchedgoods.stock
        except:
            return obj.stock

    def get_market_code(self, obj):
        try:
            user = self.context.get('user', None)
            launchedgoods = LaunchedGoods.objects.filter(level_id=user.level_id, goods_id=obj.id).first()
            if launchedgoods:
                if not launchedgoods.market_url:
                    # access_token = '89_UkeXzDxp6UXzw-JFsWbrGC0qJDkpNdsnNf3g2J4CiNukTjo0TqwRbJtsnqcWpJxs3S2m5WPa6OLuW_KhNTq9AoBUBAZWHJlEjZqFY5YWYjY4vbeVMh2BCWIojakJWScADAANJ'
                    redis_conn = get_redis_connection("scheme")
                    access_token = redis_conn.get('wyh_access_token')
                    if access_token is None:
                        access_token = redis_scheme_token_wyh()
                    else:
                        access_token = access_token.decode()
                    url = f'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token={access_token}'
                    body = {
                        "page": "pages/pro_detail/pro_detail",
                        "scene": f"gid={obj.id}&lid={launchedgoods.level_id}",
                        "is_hyaline": True
                    }
                    response = requests.post(url=url, json=body)
                    try:
                        if response.json()['errcode'] != 0:
                            access_token = redis_scheme_token_wyh()
                            url = f'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token={access_token}'
                            response = requests.post(url=url, json=body)
                    except:
                        pass
                    reslut = response.content
                    market_code = pic_upload(reslut)
                    market_url = f'https://qrcode.sutpay.com/business/market_goods/?goods_id={obj.id}&level_id={launchedgoods.level_id}'
                    # merchant_home_qrcode = f'youhuiquanyi/{obj.wyfMerchantID}/merchant_home.png'
                    # common_qrcode_url = make_qrcode(obj.wyfMerchantID, merchant_home_url, merchant_home_qrcode)
                    launchedgoods.market_url = market_url
                    launchedgoods.market_code = market_code
                    launchedgoods.save()
                    return f'https://circle.sutpay.cn/{market_code}'

                    # market_url = f'https://qrcode.sutpay.com/business/market_goods/?goods_id={obj.id}&level_id={launchedgoods.level_id}'
                    # market_code = make_qrcode1(obj.merchant.wyfMerchantID, market_url, None)
                    # launchedgoods.market_url = market_url
                    # launchedgoods.market_code = market_code
                    # launchedgoods.save()
                    # return f'https://circle.sutpay.cn/{market_code}'
                else:
                    return launchedgoods.market_code.url
            else:
                return ''
        except:
            return ''


class ActivityLevelListModelSerializer(serializers.ModelSerializer):

    activity = serializers.SerializerMethodField(read_only=True)
    remain_point_rate = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = ActivityLevel
        fields = ['id', 'activity', 'remain_point_rate']

    def get_remain_point_rate(self, obj):
        try:
            p_wait_rate = f"{(Decimal(obj.p_remain_point / obj.p_max_point) * Decimal('100')).quantize(Decimal('0'))}"
            return p_wait_rate
        except:
            return ''

    def get_activity(self, obj):
        data = {}
        data['name'] = ''
        data['activity_id'] = ''
        data['available_time'] = ''
        data['activity_state'] = ''
        data['activity_state_str'] = ''
        try:
            activity = obj.activity
            data['name'] = activity.name
            data['activity_id'] = activity.activity_id
            data['available_time'] = f'{activity.available_begin_time.strftime("%Y.%m.%d %H:%M:%S")}-{activity.available_end_time.strftime("%Y.%m.%d %H:%M:%S")}'
            data['activity_state'] = activity.activity_state
            data['activity_state_str'] = activity.get_activity_state_display()
        except:
            pass
        return data


class ActivityLevelRetrieveModelSerializer(serializers.ModelSerializer):

    activity = serializers.SerializerMethodField(read_only=True)
    level_name = serializers.SerializerMethodField(read_only=True)
    p_remain_point = serializers.SerializerMethodField(read_only=True)
    p_max_point = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = ActivityLevel
        fields = ['id', 'activity', 'p_remain_point', 'p_max_point', 'remain_point', 'level_name']

    def get_p_remain_point(self, obj):
        try:
            p_remain_point = str(int(obj.p_remain_point))
            if len(p_remain_point) >= 3:
                return f'{p_remain_point[:-2]},{p_remain_point[-2:]}'
            else:
                return p_remain_point
        except:
            return '0'

    def get_p_max_point(self, obj):
        try:
            p_max_point = str(int(obj.p_max_point))
            if len(p_max_point) >= 3:
                return f'{p_max_point[:-2]},{p_max_point[-2:]}'
            else:
                return p_max_point
        except:
            return '0'

    def get_level_name(self, obj):
        try:
            return obj.level.name
        except:
            return ''

    # def get_remain_point_rate(self, obj):
    #     try:
    #         p_wait_rate = f"{(Decimal(obj.p_remain_point / obj.p_max_point) * Decimal('100')).quantize(Decimal('0.00'))}%"
    #         return p_wait_rate
    #     except:
    #         return ''

    def get_activity(self, obj):
        data = {}
        data['name'] = ''
        data['activity_id'] = ''
        data['available_time'] = ''
        data['available_end_time'] = ''
        data['activity_state'] = ''
        data['activity_state_str'] = ''
        try:
            activity = obj.activity
            data['name'] = activity.name
            data['activity_id'] = activity.activity_id
            data['available_time'] = f'{activity.available_begin_time.strftime("%Y.%m.%d")}-{activity.available_end_time.strftime("%Y.%m.%d")}'
            data['available_end_time'] = f'{activity.available_end_time.strftime("%Y.%m.%d")}'
            data['activity_state'] = activity.activity_state
            data['activity_state_str'] = activity.get_activity_state_display()
        except:
            pass
        return data


class ActivityDataListModelSerializer(serializers.ModelSerializer):

    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    state_str = serializers.CharField(source='get_state_display', read_only=True)
    mobile = serializers.SerializerMethodField(read_only=True)
    point = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = ActivityData
        fields = ['id', 'create_time', 'state_str', 'state', 'mobile', 'point']

    def get_mobile(self, obj):
        try:
            mobile = obj.customer_user.mobile
            return f'{mobile[:3]}****{mobile[-4:]}'
        except:
            return ''

    def get_point(self, obj):
        try:
            point = str(int(obj.point))
            if len(point) >= 3:
                return f'{point[:-2]},{point[-2:]}'
            else:
                return point
        except:
            return '0'


class ActivityDataRetrieveModelSerializer(serializers.ModelSerializer):

    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    received_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    expired_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    use_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    state_str = serializers.CharField(source='get_state_display', read_only=True)
    customer_mobile = serializers.SerializerMethodField(read_only=True)
    customer_name = serializers.SerializerMethodField(read_only=True)
    activity_name = serializers.SerializerMethodField(read_only=True)
    level_name = serializers.SerializerMethodField(read_only=True)
    companyuser_name = serializers.SerializerMethodField(read_only=True)
    point = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = ActivityData
        fields = ['id', 'create_time', 'state_str', 'state', 'customer_mobile', 'point', 'activity_name', 'level_name', 'companyuser_name',
                  'received_time', 'expired_time', 'use_time', 'customer_name']

    def get_point(self, obj):
        try:
            point = str(int(obj.point))
            if len(point) >= 3:
                return f'{point[:-2]},{point[-2:]}'
            else:
                return point
        except:
            return '0'

    def get_customer_mobile(self, obj):
        try:
            mobile = obj.customer_user.mobile
            return f'{mobile[:3]}****{mobile[-4:]}'
        except:
            return ''

    def get_customer_name(self, obj):
        try:
            realname = obj.customer_user.realname
            return realname.replace(realname[-2], '*', 1)
        except:
            return ''

    def get_activity_name(self, obj):
        try:
            return obj.activity.name
        except:
            return ''

    def get_level_name(self, obj):
        try:
            return obj.level.name
        except:
            return ''

    def get_companyuser_name(self, obj):
        try:
            nickname = obj.companyuser.nickname
            return nickname.replace(nickname[-2], '*', 1)
        except:
            return ''


class ManagerUserListModelSerializer(serializers.ModelSerializer):

    is_active_str = serializers.CharField(source='get_is_active_display', read_only=True)
    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    role_name = serializers.SerializerMethodField(read_only=True)
    is_admin = serializers.SerializerMethodField(read_only=True)
    mobile = serializers.SerializerMethodField(read_only=True)
    username = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = User
        fields = ['id', 'username', 'mobile', 'header', 'is_active', 'is_active_str', 'create_time', 'role_id', 'role_name', 'is_admin']

    def get_username(self, obj):
        try:
            username = obj.username
            return username.replace(username[-2], '*', 1)
        except:
            return ''

    def get_mobile(self, obj):
        try:
            return f'{obj.mobile[:3]}****{obj.mobile[-4:]}'
        except:
            return ''

    def get_role_name(self, obj):
        try:
            return obj.role.name
        except:
            return ''

    def get_is_admin(self, obj):
        try:
            return obj.role.is_admin
        except:
            return ''


class ManagerUserRetrieveModelSerializer(serializers.ModelSerializer):

    is_active_str = serializers.CharField(source='get_is_active_display', read_only=True)
    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    role_name = serializers.SerializerMethodField(read_only=True)
    level_name = serializers.SerializerMethodField(read_only=True)
    mobile = serializers.SerializerMethodField(read_only=True)
    username = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = User
        fields = ['id', 'username', 'mobile', 'header', 'is_active', 'is_active_str', 'create_time', 'account',
                  'role_name', 'level_name', 'role_id', 'level_id']

    def get_username(self, obj):
        try:
            username = obj.username
            return username.replace(username[-2], '*', 1)
        except:
            return ''

    def get_mobile(self, obj):
        try:
            return f'{obj.mobile[:3]}****{obj.mobile[-4:]}'
        except:
            return ''

    def get_level_name(self, obj):
        try:
            return obj.level.name
        except:
            return ''

    def get_role_name(self, obj):
        try:
            return obj.role.name
        except:
            return ''


class LevelListSerializer(serializers.ModelSerializer):

    class Meta:
        model = Level
        fields = ('id', 'prov_name', 'city_name', 'district_name', 'branch_name', 'orgId', 'account')


class CashActivityLevelListModelSerializer(serializers.ModelSerializer):

    activity = serializers.SerializerMethodField(read_only=True)
    remain_amount_rate = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = CashActivityLevel
        fields = ['id', 'activity', 'remain_amount_rate']

    def get_remain_amount_rate(self, obj):
        try:
            cash_activity = obj.cash_activity
            if cash_activity.activity_type in [1, 2, 3]:
                p_wait_rate = f"{(Decimal(obj.p_remain_amount / obj.p_max_amount) * Decimal('100')).quantize(Decimal('0'))}"
                return p_wait_rate
            else:
                p_wait_rate = f"{(Decimal(cash_activity.remain_amount / cash_activity.max_amount) * Decimal('100')).quantize(Decimal('0'))}"
                return p_wait_rate
        except:
            return ''

    def get_activity(self, obj):
        data = {}
        data['name'] = ''
        data['activity_id'] = ''
        data['available_time'] = ''
        data['activity_state'] = ''
        data['activity_state_str'] = ''
        try:
            now_date = datetime.datetime.now()
            activity = obj.cash_activity
            data['name'] = activity.name
            data['activity_id'] = activity.activity_id
            data['available_time'] = f'{activity.available_begin_time.strftime("%Y.%m.%d %H:%M:%S")}-{activity.available_end_time.strftime("%Y.%m.%d %H:%M:%S")}'
            if activity.activity_state != 4 and activity.available_end_time < now_date:
                activity.activity_state = 4
                activity.save()
                data['activity_state'] = 4
                data['activity_state_str'] = '已结束'
            else:
                data['activity_state'] = activity.activity_state
                data['activity_state_str'] = activity.get_activity_state_display()
        except:
            pass
        return data


class CashActivityRuleModelSerializer(serializers.ModelSerializer):

    class Meta:
        model = CashActivityRule
        fields = ['id', 'amount', 'probability']


class CashActivityLevelRetrieveModelSerializer(serializers.ModelSerializer):

    activity = serializers.SerializerMethodField(read_only=True)
    level_name = serializers.SerializerMethodField(read_only=True)
    cashactivityrule_set = serializers.SerializerMethodField(read_only=True)
    is_auth = serializers.SerializerMethodField(read_only=True)
    p_unclaimed_amount = serializers.SerializerMethodField(read_only=True)
    p_unclaimed_rate = serializers.SerializerMethodField(read_only=True)
    p_remain_rate = serializers.SerializerMethodField(read_only=True)
    p_receive_rate = serializers.SerializerMethodField(read_only=True)
    remain_amount = serializers.SerializerMethodField(read_only=True)
    p_max_amount = serializers.SerializerMethodField(read_only=True)
    p_remain_amount = serializers.SerializerMethodField(read_only=True)
    level = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = CashActivityLevel
        fields = ['id', 'activity', 'p_remain_amount', 'p_max_amount', 'remain_amount', 'level_name', 'cashactivityrule_set', 'is_auth',
                  'p_take_amount', 'p_receive_amount', 'p_unclaimed_amount', 'p_unclaimed_rate', 'p_remain_rate', 'p_receive_rate', 'level']

    def get_remain_amount(self, obj):
        try:
            cash_activity = self.context.get('cash_activity', None)
            if cash_activity.activity_type in [1, 2, 3]:
                return obj.remain_amount
            else:
                return cash_activity.remain_amount
        except:
            return obj.remain_amount

    def get_p_remain_amount(self, obj):
        try:
            cash_activity = self.context.get('cash_activity', None)
            if cash_activity.activity_type in [1, 2, 3]:
                return obj.p_remain_amount
            else:
                return cash_activity.remain_amount
        except:
            return obj.p_remain_amount

    def get_p_max_amount(self, obj):
        try:
            cash_activity = self.context.get('cash_activity', None)
            if cash_activity.activity_type in [1, 2, 3]:
                return obj.p_max_amount
            else:
                return cash_activity.max_amount
        except:
            return obj.p_max_amount

    def get_level(self, obj):
        try:
            return obj.level.level
        except:
            return 4

    def get_p_remain_rate(self, obj):
        try:
            cash_activity = self.context.get('cash_activity', None)
            if cash_activity.activity_type in [1, 2, 3]:
                p_remain_rate = f"{(Decimal(obj.p_remain_amount / obj.p_max_amount) * Decimal('100')).quantize(Decimal('0.00'))}%"
            else:
                p_remain_rate = f"{(Decimal(cash_activity.remain_amount / cash_activity.max_amount) * Decimal('100')).quantize(Decimal('0.00'))}%"
            return p_remain_rate
        except:
            return ''

    def get_p_receive_rate(self, obj):
        try:
            cash_activity = self.context.get('cash_activity', None)
            if cash_activity.activity_type in [1, 2, 3]:
                p_receive_rate = f"{(Decimal(obj.p_receive_amount / obj.p_max_amount) * Decimal('100')).quantize(Decimal('0.00'))}%"
            else:
                p_receive_rate = f"{(Decimal(obj.p_receive_amount / cash_activity.max_amount) * Decimal('100')).quantize(Decimal('0.00'))}%"
            return p_receive_rate
        except:
            return ''

    def get_p_unclaimed_rate(self, obj):
        try:
            cash_activity = self.context.get('cash_activity', None)
            p_unclaimed_amount = obj.p_take_amount - obj.p_receive_amount
            if cash_activity.activity_type in [1, 2, 3]:
                p_unclaimed_rate = f"{(Decimal(p_unclaimed_amount / obj.p_max_amount) * Decimal('100')).quantize(Decimal('0.00'))}%"
            else:
                p_unclaimed_rate = f"{(Decimal(p_unclaimed_amount / cash_activity.max_amount) * Decimal('100')).quantize(Decimal('0.00'))}%"
            return p_unclaimed_rate
        except:
            return ''

    def get_p_unclaimed_amount(self, obj):
        try:
            p_unclaimed_amount = obj.p_take_amount - obj.p_receive_amount
            return p_unclaimed_amount
        except:
            return ''

    def get_is_auth(self, obj):
        try:
            cash_activity = self.context.get('cash_activity', None)
            if cash_activity.activity_state != 2:
                return 0
            if cash_activity.activity_type in [1, 2, 3]:
                if cash_activity.activity_type == 1:
                    if obj.is_auth == 1:
                        remain_amount = obj.remain_amount
                        if cash_activity.min_distributed_amount > remain_amount:
                            return 2
                        else:
                            return 1
                    else:
                        return obj.is_auth
                else:
                    if obj.is_auth == 1:
                        cashactivityrule = obj.cash_activity.cashactivityrule_set.filter(is_delete=0).order_by('amount').first()
                        remain_amount = obj.remain_amount
                        if cashactivityrule:
                            if cashactivityrule.amount > remain_amount:
                                return 2
                            else:
                                return 1
                        else:
                            return 1
                    else:
                        return obj.is_auth
            else:
                if cash_activity.activity_type == 4:
                    if obj.is_auth == 1:
                        remain_amount = cash_activity.remain_amount
                        if cash_activity.min_distributed_amount > remain_amount:
                            return 2
                        else:
                            return 1
                    else:
                        return obj.is_auth
                else:
                    if obj.is_auth == 1:
                        cashactivityrule = cash_activity.cashactivityrule_set.filter(is_delete=0).order_by('amount').first()
                        remain_amount = cash_activity.remain_amount
                        if cashactivityrule:
                            if cashactivityrule.amount > remain_amount:
                                return 2
                            else:
                                return 1
                        else:
                            return 1
                    else:
                        return obj.is_auth
        except:
            return obj.is_auth

    def get_cashactivityrule_set(self, obj):
        try:
            cash_activity = self.context.get('cash_activity', None)
            if cash_activity.activity_type in [1, 2, 3]:
                remain_amount = obj.remain_amount
            else:
                remain_amount = cash_activity.remain_amount
            cashactivityrule_set = cash_activity.cashactivityrule_set.filter(is_delete=0, amount__lte=remain_amount, probability__gt=0)
            return CashActivityRuleModelSerializer(cashactivityrule_set, many=True).data
        except:
            return []

    def get_level_name(self, obj):
        try:
            return obj.level.name
        except:
            return ''

    # def get_remain_point_rate(self, obj):
    #     try:
    #         p_wait_rate = f"{(Decimal(obj.p_remain_point / obj.p_max_point) * Decimal('100')).quantize(Decimal('0.00'))}%"
    #         return p_wait_rate
    #     except:
    #         return ''

    def get_activity(self, obj):
        data = {}
        data['name'] = ''
        data['activity_id'] = ''
        data['available_time'] = ''
        data['available_end_time'] = ''
        data['activity_state'] = ''
        data['activity_state_str'] = ''
        data['activity_type'] = ''
        data['activity_type_str'] = ''
        data['max_distributed_amount'] = ''
        data['min_distributed_amount'] = ''
        data['is_white'] = 0
        data['is_white_merchant'] = 0
        try:
            activity = self.context.get('cash_activity', None)
            data['name'] = activity.name
            data['activity_id'] = activity.activity_id
            data['available_time'] = f'{activity.available_begin_time.strftime("%Y.%m.%d")}-{activity.available_end_time.strftime("%Y.%m.%d")}'
            data['available_end_time'] = f'{activity.available_end_time.strftime("%Y.%m.%d")}'
            data['activity_state'] = activity.activity_state
            data['activity_state_str'] = activity.get_activity_state_display()
            if activity.activity_type == 4:
                data['activity_type'] = 1
            elif activity.activity_type == 5:
                data['activity_type'] = 2
            elif activity.activity_type == 6:
                data['activity_type'] = 3
            else:
                data['activity_type'] = activity.activity_type
            data['activity_type_str'] = activity.get_activity_type_display()
            if activity.activity_type in [1, 2, 3]:
                if obj.remain_amount < activity.max_distributed_amount:
                    max_distributed_amount = obj.remain_amount
                else:
                    max_distributed_amount = activity.max_distributed_amount
            else:
                if activity.remain_amount < activity.max_distributed_amount:
                    max_distributed_amount = activity.remain_amount
                else:
                    max_distributed_amount = activity.max_distributed_amount
            data['max_distributed_amount'] = max_distributed_amount
            data['min_distributed_amount'] = activity.min_distributed_amount
            data['is_white'] = activity.is_white
            data['is_limit_white'] = activity.is_limit_white
            data['is_white_merchant'] = activity.is_white_merchant
            data['total_white_accout'] = activity.white_accout
            data['white_accout'] = 0
            if activity.is_limit_white == 1:
                user = self.context.get('user', None)
                white_accout = CashActivityWhiteTable.objects.filter(cashactivity_id=activity.id, add_user_id=user.id).count()
                data['white_accout'] = white_accout
        except:
            pass
        return data


class CashActivityDataListModelSerializer(serializers.ModelSerializer):

    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    customer_mobile = serializers.SerializerMethodField(read_only=True)
    amount = serializers.SerializerMethodField(read_only=True)
    state_str = serializers.CharField(source='get_state_display', read_only=True)

    class Meta:
        model = CashActivityData
        fields = ['id', 'create_time', 'state_str', 'state', 'customer_mobile', 'amount']

    def get_amount(self, obj):
        try:
            if obj.cash_activity.activity_type in [3, 6]:
                if obj.state in [2]:
                    return obj.amount
                else:
                    return '??'
            else:
                return obj.amount
        except:
            return obj.amount

    def get_customer_mobile(self, obj):
        try:
            mobile = obj.customer_user.mobile
            return f'{mobile[:3]}****{mobile[-4:]}'
        except:
            return ''


class CashActivityDataRetrieveModelSerializer(serializers.ModelSerializer):

    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    received_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    expired_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    use_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    state_str = serializers.CharField(source='get_state_display', read_only=True)
    customer_mobile = serializers.SerializerMethodField(read_only=True)
    customer_name = serializers.SerializerMethodField(read_only=True)
    activity_name = serializers.SerializerMethodField(read_only=True)
    level_name = serializers.SerializerMethodField(read_only=True)
    companyuser_name = serializers.SerializerMethodField(read_only=True)
    amount = serializers.SerializerMethodField(read_only=True)
    mchid = serializers.SerializerMethodField(read_only=True)
    payeeFullName = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = CashActivityData
        fields = ['id', 'create_time', 'state_str', 'state', 'customer_mobile', 'amount', 'activity_name', 'level_name', 'companyuser_name',
                  'received_time', 'expired_time', 'use_time', 'customer_name', 'payment_no', 'return_msg', 'mchid', 'payeeFullName']

    def get_payeeFullName(self, obj):
        try:
            if obj.payeeFullName:
                return obj.payeeFullName
            else:
                return ''
        except:
            return ''

    def get_mchid(self, obj):
        try:
            if obj.mchid == 'alipay':
                return '支付宝'
            else:
                return '微信'
        except:
            return ''

    def get_amount(self, obj):
        try:
            if obj.cash_activity.activity_type in [3, 6]:
                if obj.state in [2]:
                    return obj.amount
                else:
                    return '??'
            else:
                return obj.amount
        except:
            return obj.amount

    def get_customer_mobile(self, obj):
        try:
            mobile = obj.customer_user.mobile
            return f'{mobile[:3]}****{mobile[-4:]}'
        except:
            return ''

    def get_customer_name(self, obj):
        try:
            realname = obj.customer_user.realname
            return realname.replace(realname[-2], '*', 1)
        except:
            return ''

    def get_activity_name(self, obj):
        try:
            return obj.cash_activity.name
        except:
            return ''

    def get_level_name(self, obj):
        try:
            return obj.level.name
        except:
            return ''

    def get_companyuser_name(self, obj):
        try:
            nickname = obj.companyuser.nickname
            return nickname.replace(nickname[-2], '*', 1)
        except:
            return ''


class CashActivityLevelStatisticalModelSerializer(serializers.ModelSerializer):

    level_name = serializers.SerializerMethodField(read_only=True)
    p_unclaimed_amount = serializers.SerializerMethodField(read_only=True)
    p_unclaimed_rate = serializers.SerializerMethodField(read_only=True)
    p_remain_rate = serializers.SerializerMethodField(read_only=True)
    p_receive_rate = serializers.SerializerMethodField(read_only=True)
    p_remain_amount = serializers.SerializerMethodField(read_only=True)
    p_max_amount = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = CashActivityLevel
        fields = ['id', 'level_name', 'p_max_amount', 'p_remain_amount', 'p_take_amount', 'p_unclaimed_amount', 'p_receive_amount',
                  'p_unclaimed_rate', 'p_receive_rate', 'p_remain_rate']

    def get_p_max_amount(self, obj):
        try:
            activity = self.context.get('cash_activity', None)
            if activity.activity_type in [1, 2, 3]:
                return obj.p_max_amount
            else:
                return activity.max_amount
        except:
            return obj.p_max_amount

    def get_p_remain_amount(self, obj):
        try:
            activity = self.context.get('cash_activity', None)
            if activity.activity_type in [1, 2, 3]:
                return obj.p_remain_amount
            else:
                return activity.remain_amount
        except:
            return obj.p_remain_amount

    def get_p_remain_rate(self, obj):
        try:
            activity = self.context.get('cash_activity', None)
            if activity.activity_type in [1, 2, 3]:
                p_remain_rate = f"{(Decimal(obj.p_remain_amount / obj.p_max_amount) * Decimal('100')).quantize(Decimal('0.00'))}%"
            else:
                p_remain_rate = f"{(Decimal(activity.remain_amount / activity.max_amount) * Decimal('100')).quantize(Decimal('0.00'))}%"
            return p_remain_rate
        except:
            return ''

    def get_p_receive_rate(self, obj):
        try:
            activity = self.context.get('cash_activity', None)
            if activity.activity_type in [1, 2, 3]:
                p_receive_rate = f"{(Decimal(obj.p_receive_amount / obj.p_max_amount) * Decimal('100')).quantize(Decimal('0.00'))}%"
            else:
                p_receive_rate = f"{(Decimal(obj.p_receive_amount / activity.max_amount) * Decimal('100')).quantize(Decimal('0.00'))}%"
            return p_receive_rate
        except:
            return ''

    def get_p_unclaimed_rate(self, obj):
        try:
            activity = self.context.get('cash_activity', None)
            p_unclaimed_amount = obj.p_take_amount - obj.p_receive_amount
            if activity.activity_type in [1, 2, 3]:
                p_unclaimed_rate = f"{(Decimal(p_unclaimed_amount / obj.p_max_amount) * Decimal('100')).quantize(Decimal('0.00'))}%"
            else:
                p_unclaimed_rate = f"{(Decimal(p_unclaimed_amount / activity.max_amount) * Decimal('100')).quantize(Decimal('0.00'))}%"
            return p_unclaimed_rate
        except:
            return ''

    def get_level_name(self, obj):
        try:
            return obj.level.name
        except:
            return ''

    def get_p_unclaimed_amount(self, obj):
        try:
            p_unclaimed_amount = obj.p_take_amount - obj.p_receive_amount
            return p_unclaimed_amount
        except:
            return ''


class CustomizeActivityLevelListModelSerializer(serializers.ModelSerializer):

    activity = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = CustomizeActivityLevel
        fields = ['id', 'activity']

    def get_activity(self, obj):
        data = {}
        data['name'] = ''
        data['activity_id'] = ''
        data['available_time'] = ''
        data['activity_status'] = ''
        data['activity_status_str'] = ''
        data['prize_type'] = ''
        try:
            now_date = datetime.datetime.now()
            activity = obj.customizeactivity
            data['name'] = activity.activity_name
            data['activity_id'] = activity.activity_id
            data['available_time'] = f'{activity.available_begin_time.strftime("%Y.%m.%d %H:%M:%S")}-{activity.available_end_time.strftime("%Y.%m.%d %H:%M:%S")}'
            if activity.activity_status != 2 and activity.available_end_time < now_date:
                activity.activity_status = 2
                activity.save()
                data['activity_status'] = 2
                data['activity_status_str'] = '已结束'
            else:
                data['activity_status'] = activity.activity_status
                data['activity_status_str'] = activity.get_activity_status_display()
            data['prize_type'] = activity.prize_type.split(',')
            # data['prize_type_str'] = activity.prize_type
        except:
            pass
        return data


class CustomizeActivityRulesModelSerializer(serializers.ModelSerializer):

    prize_type_str = serializers.CharField(source='get_prize_type_display', read_only=True)
    activity_info = serializers.SerializerMethodField(read_only=True)
    count = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = CustomizeActivityRules
        fields = ['id', 'prize_type', 'prize_type_str', 'activity_info', 'count']

    def get_count(self, obj):
        try:
            if obj.customizeactivity.activity_type == 11:
                return obj.count
            else:
                return 0
        except:
            return 0

    def get_activity_info(self, obj):
        data = {}
        data['id'] = ''
        data['activity_name'] = ''
        data['rule'] = ''
        try:
            prize_type = obj.prize_type
            if prize_type in [1, 2, 7, 8]:
                alidiscountcoupon = obj.alidiscountcoupon
                data['id'] = alidiscountcoupon.id
                data['activity_name'] = alidiscountcoupon.activity_name
                data['rule'] = alidiscountcoupon.floor_amount
            else:
                cashactivity = obj.cashactivity
                cashactivityrule_set = cashactivity.cashactivityrule_set.filter(is_delete=0).order_by('amount')
                result = ''
                for cashactivityrule in cashactivityrule_set:
                    result += f'¥{cashactivityrule.amount},'
                data['id'] = cashactivity.id
                data['activity_name'] = cashactivity.name
                data['rule'] = result[:-1]
        except:
            pass
        return data


class CustomizeActivityLevelRetrieveModelSerializer(serializers.ModelSerializer):

    activity = serializers.SerializerMethodField(read_only=True)
    level_name = serializers.SerializerMethodField(read_only=True)
    drawdown_platform_id = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = CustomizeActivityLevel
        fields = ['id', 'activity', 'common_qrcode', 'level_name', 'max_number', 'take_number', 'remain_number', 'receive_number', 'drawdown_platform_id']

    def get_drawdown_platform_id(self, obj):
        try:
            return obj.customizeactivity.drawdown_platform_id
        except:
            return 3

    def get_activity(self, obj):
        data = {}
        data['name'] = ''
        data['activity_id'] = ''
        data['available_time'] = ''
        data['activity_status'] = ''
        data['activity_status_str'] = ''
        data['prize_type'] = ''
        data['activity_type'] = ''
        data['activity_type_str'] = ''
        data['activity_rules'] = ''
        data['common_qrcode'] = ''
        data['is_sign'] = ''
        try:
            now_date = datetime.datetime.now()
            activity = obj.customizeactivity
            if activity.drawdown_platform_id == 4:
                data['is_sign'] = 1
            else:
                data['is_sign'] = 0
            data['name'] = activity.activity_name
            data['activity_id'] = activity.activity_id
            data['available_time'] = f'{activity.available_begin_time.strftime("%Y.%m.%d")}-{activity.available_end_time.strftime("%Y.%m.%d")}'
            if activity.activity_status != 2 and activity.available_end_time < now_date:
                activity.activity_status = 2
                activity.save()
                data['activity_status'] = 2
                data['activity_status_str'] = '已结束'
            else:
                data['activity_status'] = activity.activity_status
                data['activity_status_str'] = activity.get_activity_status_display()
            data['prize_type'] = activity.prize_type.split(',')
            data['activity_type'] = activity.activity_type
            data['activity_type_str'] = activity.get_activity_type_display()
            customizeactivityrules_set = activity.customizeactivityrules_set.all()
            data['activity_rules'] = CustomizeActivityRulesModelSerializer(customizeactivityrules_set, many=True).data
            if activity.activity_type == 11:
                data['common_qrcode'] = ''
            else:
                data['common_qrcode'] = activity.common_qrcode.url
        except:
            pass
        return data

    def get_level_name(self, obj):
        try:
            return obj.level.name
        except:
            return ''


class CustomizeActivityFlipCARDSListModelSerializer(serializers.ModelSerializer):

    received_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    open_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    open_status_str = serializers.CharField(source='get_open_status_display', read_only=True)
    win_type_str = serializers.CharField(source='get_win_type_display', read_only=True)
    customercser_mobile = serializers.SerializerMethodField(read_only=True)
    activity_name = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = CustomizeActivityFlipCARDS
        fields = ['id', 'open_status', 'open_status_str', 'received_time', 'customercser_mobile', 'activity_name', 'open_time', 'win_type', 'win_type_str']

    def get_customercser_mobile(self, obj):
        try:
            mobile = obj.user.mobile
            return f'{mobile[:3]}****{mobile[-4:]}'
        except:
            return ''

    def get_activity_name(self, obj):
        try:
            if obj.win_type in [1, 2, 7, 8]:
                return obj.alidiscountcoupon.activity_name
            elif obj.win_type == 3:
                return obj.cashactivity.name
            else:
                return ''
        except:
            return ''


class CustomizeActivityFlipCARDSRetrieveModelSerializer(serializers.ModelSerializer):

    received_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    open_status_str = serializers.CharField(source='get_open_status_display', read_only=True)
    customercser_mobile = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = CustomizeActivityFlipCARDS
        fields = ['id', 'open_status', 'open_status_str', 'received_time', 'customercser_mobile']

    def get_customercser_mobile(self, obj):
        try:
            mobile = obj.user.mobile
            return f'{mobile[:3]}****{mobile[-4:]}'
        except:
            return ''


class MerchantBusinessQRCodeListModelSerializer(serializers.ModelSerializer):

    is_c_bind_str = serializers.CharField(source='get_is_c_bind_display', read_only=True)
    is_achieve_str = serializers.CharField(source='get_is_achieve_display', read_only=True)
    award_status_str = serializers.CharField(source='get_award_status_display', read_only=True)
    bind_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    merchant = serializers.SerializerMethodField(read_only=True)
    customeruservice = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = MerchantBusinessQRCode
        fields = ['id', 'sn', 'bind_time', 'merchant', 'is_c_bind', 'is_c_bind_str', 'award_status', 'award_status_str', 'is_achieve', 'is_achieve_str',
                  'customeruservice']

    def get_merchant(self, obj):
        data = {}
        data['merchant_id'] = ''
        data['business_no'] = ''
        data['merchant_name'] = ''
        data['branch_name'] = ''
        try:
            merchant = obj.merchant
            if merchant:
                level = merchant.level
                data['merchant_id'] = merchant.id
                data['business_no'] = merchant.wyfMerchantID
                data['merchant_name'] = merchant.name
                data['branch_name'] = level.branch_name
        except:
            pass
        return data

    def get_customeruservice(self, obj):
        try:
            if obj.is_c_bind == 0:
                merchant = obj.merchant
                managerName = merchant.managerName
                managermobile = merchant.managermobile
                managerName = managerName.replace(managerName[-2], '*', 1)
                managermobile = f'{managermobile[:3]}****{managermobile[-4:]}'
                return f'{managerName}({managermobile})'.replace('None', '')
            else:
                return ''
        except:
            return ''


class MerchantBusinessQRCodeRetrieveModelSerializer(serializers.ModelSerializer):

    is_c_bind_str = serializers.CharField(source='get_is_c_bind_display', read_only=True)
    is_achieve_str = serializers.CharField(source='get_is_achieve_display', read_only=True)
    award_status_str = serializers.CharField(source='get_award_status_display', read_only=True)
    bind_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    c_bind_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    award_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    merchant = serializers.SerializerMethodField(read_only=True)
    customeruservice = serializers.SerializerMethodField(read_only=True)
    visit_count = serializers.SerializerMethodField(read_only=True)
    cashactivitydata = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = MerchantBusinessQRCode
        fields = ['id', 'sn', 'bind_time', 'merchant', 'is_c_bind', 'is_c_bind_str', 'c_bind_time', 'customeruservice',
                  'inviter_count', 'inviter_total_count', 'award_time', 'visit_count', 'award_status', 'award_status_str', 'cashactivitydata',
                  'is_achieve', 'is_achieve_str']

    def get_cashactivitydata(self, obj):
        data = {}
        data['id'] = ''
        data['activity_name'] = ''
        data['received_time'] = ''
        data['amount'] = ''
        try:
            cashactivitydata = obj.cashactivitydata
            if cashactivitydata:
                cash_activity = cashactivitydata.cash_activity
                data['id'] = cashactivitydata.id
                data['activity_name'] = cash_activity.name
                data['amount'] = '5.00'
                data['state'] = cashactivitydata.state
                data['received_time'] = cashactivitydata.received_time.strftime("%Y-%m-%d %H:%M:%S")
            else:
                if obj.is_bind == 1:
                    companyuser = obj.user
                    companyuser_id = companyuser.id
                    date_now = datetime.datetime.now()
                    nonce_str = random_str()
                    cash_activity_id = 355
                    amount = Decimal('5')
                    cash_activity = CashActivity.objects.get(id=cash_activity_id)
                    cashactivitydata_data = {}
                    cashactivitydata_data['companyuser_id'] = companyuser_id
                    cashactivitydata_data['cash_activity_id'] = cash_activity.id
                    cashactivitydata_data['amount'] = amount
                    cashactivitydata_data['create_time'] = date_now
                    cashactivitydata_data['nonce_str'] = nonce_str
                    cashactivitydata_data['desc'] = cash_activity.name
                    cashactivitydata_data['mobile'] = companyuser.mobile
                    cashactivitydata_data['openid'] = companyuser.openid
                    cashactivitydata_data['appid'] = 'wxb67b94c00d7cd83f'
                    cashactivitydata_data['partner_trade_no'] = f'{date_now.strftime("%Y%m%d%H%M%S")}{"%06d" % randint(0, 999999)}{"%06d" % companyuser_id}'
                    cashactivitydata = CashActivityData.objects.create(**cashactivitydata_data)
                    while True:
                        activity = CashActivity.objects.get(id=cash_activity_id)
                        activity_origin_take_amount = activity.take_amount
                        activity_origin_remain_amount = activity.remain_amount
                        activity_new_take_amount = activity_origin_take_amount + amount
                        activity_new_remain_amount = activity_origin_remain_amount - amount
                        result = CashActivity.objects.filter(take_amount=activity_origin_take_amount,
                                                             remain_amount=activity_origin_remain_amount,
                                                             id=cash_activity_id).update(
                            take_amount=activity_new_take_amount, remain_amount=activity_new_remain_amount)
                        if result == 0:
                            continue
                        break
                    obj.cashactivitydata_id = cashactivitydata.id
                    # obj.is_achieve = 1
                    # obj.award_time = CustomerUserViceInviterRecord.objects.filter(qrcode_id=obj.id, is_inviter=1)[2].inviter_time
                    obj.save()
                    data['id'] = cashactivitydata.id
                    data['activity_name'] = cash_activity.name
                    data['amount'] = '5.00'
                    data['state'] = cashactivitydata.state
                    data['received_time'] = cashactivitydata.received_time.strftime("%Y-%m-%d %H:%M:%S")
        except:
            pass
        return data

    def get_merchant(self, obj):
        data = {}
        data['merchant_id'] = ''
        data['business_no'] = ''
        data['merchant_name'] = ''
        data['merchant_short_name'] = ''
        data['branch_name'] = ''
        try:
            merchant = obj.merchant
            if merchant:
                level = merchant.level
                data['merchant_id'] = merchant.id
                data['business_no'] = merchant.wyfMerchantID
                data['merchant_name'] = merchant.name
                data['merchant_short_name'] = merchant.short_name
                data['branch_name'] = level.branch_name
        except:
            pass
        return data

    def get_customeruservice(self, obj):
        try:
            customeruservice = obj.customeruservice
            if customeruservice:
                mobile = customeruservice.mobile
                mobile = f'{mobile[:3]}****{mobile[-4:]}'
                return f'{customeruservice.username}({mobile})'.replace('None', '')
            else:
                return ''
        except:
            return ''

    def get_visit_count(self, obj):
        try:
            visit_count = MerchantBusinessQRCodeVisit.objects.filter(qrcode_id=obj.id).count()
            return visit_count
        except:
            return 0


class MerchantBusinessQRCodeVisitListModelSerializer(serializers.ModelSerializer):

    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    customeruservice = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = MerchantBusinessQRCodeVisit
        fields = ['id', 'create_time', 'customeruservice']

    def get_customeruservice(self, obj):
        data = {}
        data['openid'] = ''
        data['mobile'] = ''
        try:
            customeruservice = obj.customeruservice
            if customeruservice:
                mobile = customeruservice.mobile
                data['openid'] = f'……{customeruservice.wyh_openid[-11:]}'
                data['mobile'] = f'{mobile[:3]}****{mobile[-4:]}'
        except:
            pass
        return data


class CustomerUserViceInviterRecordListModelSerializer(serializers.ModelSerializer):

    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    inviter_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    customeruservice = serializers.SerializerMethodField(read_only=True)
    is_inviter_str = serializers.CharField(source='get_is_inviter_display', read_only=True)

    class Meta:
        model = CustomerUserViceInviterRecord
        fields = ['id', 'create_time', 'customeruservice', 'is_inviter', 'is_inviter_str', 'inviter_time', 'inviter_time']

    def get_customeruservice(self, obj):
        data = {}
        data['realname'] = ''
        data['mobile'] = ''
        try:
            customeruservice = obj.customeruservice
            if customeruservice:
                mobile = customeruservice.mobile
                data['realname'] = customeruservice.realname if customeruservice.realname else '受邀用户'
                data['mobile'] = f'{mobile[:3]}****{mobile[-4:]}'
        except:
            pass
        return data


class NewYearsShoppingFestivalElectListModelSerializer(serializers.ModelSerializer):

    available_begin_time = serializers.DateTimeField(format="%Y.%m.%d", required=False)
    available_end_time = serializers.DateTimeField(format="%Y.%m.%d", required=False)
    is_create = serializers.SerializerMethodField(read_only=True)
    is_leaderboard = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = NewYearsShoppingFestivalElect
        fields = ['id', 'available_begin_time', 'available_end_time', 'activity_description', 'is_create', 'is_leaderboard']

    def get_is_create(self, obj):
        try:
            user = self.context.get('user')
            if obj.activity_state == 3:
                return 0
            available_begin_time = obj.available_begin_time
            available_end_time = obj.available_end_time
            today = datetime.datetime.now()
            if today >= available_end_time:
                obj.activity_state = 3
                obj.save()
                return 0
            else:
                if obj.activity_state == 1:
                    if today >= available_begin_time:
                        obj.activity_state = 2
                        obj.save()
                check_product = NewYearsShoppingFestivalElectProduct.objects.filter(manageruser_id=user.id, elect_id=obj.id)
                if check_product:
                    return 0
                return 1
        except:
            return 0

    def get_is_leaderboard(self, obj):
        try:
            today = datetime.datetime.now()
            if obj.available_begin_time > today:
                return 0
            else:
                return 1
        except:
            return 0


class NewYearsShoppingFestivalElectProductListModelSerializer(serializers.ModelSerializer):

    manageruser_name = serializers.SerializerMethodField(read_only=True)
    index = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = NewYearsShoppingFestivalElectProduct
        fields = ['id', 'product_title', 'product_intro', 'manageruser_name', 'default_image', 'index', 'like_count']

    def get_manageruser_name(self, obj):
        try:
            nickname = obj.manageruser.nickname
            return nickname.replace(nickname[-2], '*', 1)
        except:
            return ''

    def get_index(self, obj):
        try:
            if obj.is_match == 1:
                queryset = list(NewYearsShoppingFestivalElectProduct.objects.filter(is_match=1).order_by('-like_count').values_list('id', flat=True))
                return queryset.index(obj.id) + 1
            else:
                return ''
        except:
            return 0


class NewYearsShoppingFestivalElectProductRetrieveModelSerializer(serializers.ModelSerializer):

    manageruser = serializers.SerializerMethodField(read_only=True)
    index = serializers.SerializerMethodField(read_only=True)
    image_set = serializers.SerializerMethodField(read_only=True)
    is_update = serializers.SerializerMethodField(read_only=True)
    is_publish = serializers.SerializerMethodField(read_only=True)
    is_match_str = serializers.CharField(source='get_is_match_display', read_only=True)
    level_name = serializers.SerializerMethodField(read_only=True)
    level_type = serializers.SerializerMethodField(read_only=True)
    level_type_str = serializers.SerializerMethodField(read_only=True)
    is_leaderboard = serializers.SerializerMethodField(read_only=True)
    product_qrcode = serializers.SerializerMethodField(read_only=True)
    activity_description = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = NewYearsShoppingFestivalElectProduct
        fields = ['id', 'product_title', 'product_intro', 'manageruser', 'default_image', 'index', 'image_set', 'is_update',
                  'is_publish', 'is_match', 'is_match_str', 'level_name', 'level_type', 'level_type_str', 'is_leaderboard',
                  'product_qrcode', 'activity_description', 'like_count']

    def get_activity_description(self, obj):
        try:
            return obj.elect.activity_description
        except:
            return ''

    def get_product_qrcode(self, obj):
        try:
            if not obj.product_qrcode:
                product_url = f'https://qrcode.sutpay.com/business/elect_product/?product_id={obj.id}'
                product_qrcode = make_qrcode4(obj.id, product_url, None)
                obj.product_url = product_url
                obj.product_qrcode = product_qrcode
                obj.save()
                return f'https://circle.sutpay.cn/{product_qrcode}'
            else:
                return obj.product_qrcode.url
        except:
            return ''

    def get_manageruser(self, obj):
        data = {}
        data['nickname'] = ''
        data['mobile'] = ''
        data['role_name'] = ''
        try:
            manageruser = obj.manageruser
            nickname = manageruser.nickname
            mobile = manageruser.mobile
            data['nickname'] = nickname.replace(nickname[-2], '*', 1)
            data['mobile'] = f'{mobile[:3]}****{mobile[-4:]}'
            data['role_name'] = manageruser.role.name
        except:
            pass
        return data

    def get_index(self, obj):
        try:
            if obj.is_match == 1:
                queryset = list(NewYearsShoppingFestivalElectProduct.objects.filter(is_match=1).order_by('-like_count', 'id').values_list('id', flat=True))
                return queryset.index(obj.id) + 1
            else:
                return ''
        except:
            return 0

    def get_image_set(self, obj):
        data = []
        try:
            image_set = obj.newyearsshoppingfestivalelectproductpic_set.all()
            for image in image_set:
                data.append(image.image.url)
        except:
            pass
        return data

    def get_is_update(self, obj):
        try:
            if obj.elect.available_begin_time <= datetime.datetime.now():
                return 0
            user = self.context.get('user')
            if user.id == obj.manageruser_id:
                return 1
            else:
                return 0
        except:
            return 0

    def get_is_publish(self, obj):
        try:
            if obj.elect.available_begin_time <= datetime.datetime.now():
                return 0
            if obj.is_match == 0:
                user = self.context.get('user')
                if user.role_id == 3:
                    return 0
                else:
                    if user.level_id != obj.level_id:
                        return 0
                    else:
                        return 1
            else:
                return 0
        except:
            return 0

    def get_level_name(self, obj):
        try:
            return obj.level.name
        except:
            return ''

    def get_level_type_str(self, obj):
        try:
            level = obj.level.level
            if level == 1:
                return '省公司'
            elif level == 2:
                return '市公司'
            elif level == 3:
                return '区县'
            elif level == 4:
                return  '网点'
            else:
                return '信翔'
        except:
            return ''

    def get_level_type(self, obj):
        try:
            level = obj.level.level
            return level
        except:
            return ''

    def get_is_leaderboard(self, obj):
        try:
            if obj.is_match == 1:
                today = datetime.datetime.now()
                if obj.elect.available_begin_time > today:
                    return 0
                else:
                    return 1
            else:
                return 0
        except:
            return 0


class OrderGoodsCommentFileModelSerializer(serializers.ModelSerializer):

    class Meta:
        model = OrderGoodsCommentFile
        fields = ('id', 'file', 'file_type')


class GoodsCommentModelSerializer(serializers.ModelSerializer):

    ordergoodscommentfile_set = OrderGoodsCommentFileModelSerializer(many=True)
    comment_time = serializers.DateTimeField(format="%Y-%m-%d", required=False)
    username = serializers.SerializerMethodField(read_only=True)
    avatar = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = OrderGoods
        fields = ('id', 'is_commented', 'comment', 'ordergoodscommentfile_set',
                  'comment_time', 'is_anonymous', 'avatar', 'username')

    def get_username(self, obj):
        try:
            if obj.is_anonymous == 1:
                return '匿名买家'
            else:
                return obj.order.customeruservice.username
        except:
            return '匿名买家'

    def get_avatar(self, obj):
        try:
            if obj.is_anonymous == 1:
                return 'https://jinjian.sutpay.cn/image/wyh_img101.png'
            else:
                return obj.order.customeruservice.avatar
        except:
            return 'https://jinjian.sutpay.cn/image/wyh_img101.png'


class GoodsTagActivityLevelRelationModelSerializer(serializers.ModelSerializer):

    alidiscountcoupon_set = serializers.SerializerMethodField(read_only=True)
    goods_tag_activity = serializers.SerializerMethodField(read_only=True)
    goods_count = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = GoodsTagActivityLevelRelation
        fields = ('id', 'goods_tag_activity', 'alidiscountcoupon_set', 'goods_count')

    def get_goods_tag_activity(self, obj):
        data = {}
        goods_tag_activity = obj.goods_tag_activity
        data['goods_tag'] = goods_tag_activity.goods_tag
        data['activity_name'] = goods_tag_activity.activity_name
        return data

    def get_goods_count(self, obj):
        goods_tag = obj.goods_tag_activity.goods_tag
        user = self.context.get('user', None)
        return Goods.objects.filter(merchant__merchantenter__level_id=user.level_id, goods_tag=goods_tag).distinct().count()
        # return Goods.objects.filter(is_launched=1, goods_tag=goods_tag)

    def get_alidiscountcoupon_set(self,obj):
        data = []
        try:
            date_now = datetime.datetime.now()
            goods_tag_activity = obj.goods_tag_activity
            goods_tag = goods_tag_activity.goods_tag
            queryset = AliDiscountCoupon.objects.filter(coupon_status__in=[1, 3], publish_end_time__gte=date_now, goods_tag=goods_tag)[:4]
            for activity in queryset:
                data.append({
                    "activity_name": activity.activity_name,
                    "template_id": activity.template_id,
                    "floor_amount": activity.floor_amount,
                })
            return data
        except:
            return data


class CashActivityWhiteTableModelSerializer(serializers.ModelSerializer):

    add_user = serializers.SerializerMethodField(read_only=True)
    contact_name = serializers.SerializerMethodField(read_only=True)
    id_card_number = serializers.SerializerMethodField(read_only=True)
    mobile = serializers.SerializerMethodField(read_only=True)
    add_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)

    class Meta:
        model = CashActivityWhiteTable
        fields = ('mobile', 'add_user', 'add_time', 'business_no', 'contact_name', 'id_card_number')

    def get_add_user(self, obj):
        if obj.is_admin == 1:
            return '管理员'
        else:
            return f'{obj.add_user.nickname.replace(obj.add_user.nickname[-2], "*", 1)}'

    def get_contact_name(self, obj):
        try:
            return f'{obj.contact_name.replace(obj.contact_name[-2], "*", 1)}'
        except:
            return ''

    def get_id_card_number(self, obj):
        try:
            return f'{obj.id_card_number[:6]}****{obj.id_card_number[-3:]}'
        except:
            return ''

    def get_mobile(self, obj):
        try:
            return f'{obj.mobile[:3]}****{obj.mobile[-4:]}'
        except:
            return ''


class AliDiscountCouponMerchantModelSerializer(serializers.ModelSerializer):

    merchant = serializers.SerializerMethodField(read_only=True)
    channel = serializers.SerializerMethodField(read_only=True)
    # last_update_time = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = AliDiscountCouponMerchant
        fields = ['id', 'sub_mchid', 'merchant', 'channel_id', 'channel']

    def get_channel(self, obj):
        try:
            return obj.channel.name
        except:
            return ''

    def get_merchant(self, obj):
        data = {}
        data['merchant_id'] = ''
        data['merchant_name'] = ''
        data['merchant_short_name'] = ''
        data['business_no'] = ''
        data['store_logo_copy'] = ''
        try:
            merchant = obj.merchant
            data['merchant_id'] = merchant.id
            data['merchant_name'] = merchant.name
            data['merchant_short_name'] = merchant.short_name
            data['business_no'] = merchant.wyfMerchantID
            data['store_logo_copy'] = merchant.store_logo_copy.url
        except:
            pass
        return data


